反应中从父组件访问子的子状态

时间:2018-03-29 14:35:08

标签: reactjs redux

我想从父组件访问<Child2>状态。

<Parent>
   <Child1>
      <Child2>
   </Child1>
</Parent>

如何实现?

2 个答案:

答案 0 :(得分:4)

你根本不应该这样做。反应信息应始终从上到下流动。做到这一点的反应方式是lift state up to the parent并将值作为道具传递下来。在您的孩子中,当值发生变化(例如通过用户交互)时,您的回调也会作为孩子调用的道具传递,以便父级可以更新其状态:

const Child = ({ value, onChange }) => (
  <Fragment>
    <p>{value || "no value"}</p>
    <button onClick={() => onChange('changed')} >Set value</button>
  </Fragment>
);

class Parent extends Component {
  state = {
    value: null
  };

  handleChange = value => this.setState({value})

  render() {
    return <Child value={this.state.value} onChange={this.handleChange} />;
  }
}

Working example on codesandbox

这可以无限深层嵌套完成。在一个更大的应用程序中,您的状态需要在遍布组件树的多个组件中使用,您可能会达到获得PITA的程度。解决此问题的常用方法是使用redux提供的全局商店。

答案 1 :(得分:2)

避免将道具传递给多个组件的一种方法是使用反应context api。

这允许我们从MyProvider组件100个子组件中获取状态,而无需手动将支持向下传递100个子组件。

import React, { Component } from "react";
import { render } from "react-dom";

// first make a new context
const MyContext = React.createContext();

// Then Create a provider Component
class MyProvider extends Component {
  state = {
    name: "Junie",
    age: 21
  };
  render() {
    return (
      <MyContext.Provider
        value={{
          state: this.state,
          increment: () => this.setState({ age: this.state.age + 1 })
        }}
      >
        {this.props.children}
      </MyContext.Provider>
    );
  }
}

const App = () => {
  return (
    <MyProvider>
      <div>
        <p>Hello I'm the App </p>
        <Child />
      </div>
    </MyProvider>
  );
};

const Child = props => {
  return (
    <div>
      <Child2 />
    </div>
  );
};

class Child2 extends Component {
  render() {
    return (
      <div>
        <p> Im Child 2 </p>
        <MyContext.Consumer>
          {context => (
            <div>
              {" "}
              <p>
                {" "}
                Inside the context consumer: {context.state.name}{" "}
                {context.state.age}
              </p>{" "}
              <button onClick={context.increment}>Update Age </button>
            </div>
          )}
        </MyContext.Consumer>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

Edit stack overflow context example passing to second child

使用context可能就是您要找的。

还有另一种实施方式。

class Parent extends React.Component {

state={childstate:''}

getFromChild = (value) => {
 this.setState({childstate:value})
}

 render() {
  return (
   <div> 
    <Child1 getFromChild={this.getFromChild/> 
    {this.state.childstate && <div> {this.state.childstate} </div>} 
   </div>
  )
 }
}

const Child1 = (props) => <Child2 getFromChild={props.getFromChild}/>

class Child2 extends React.Component {
state={somevalue:10}

sendValue = (value) => this.props.getFromChild(value)

render() {
 return (
   <div>
    <button onClick={() => this.sendValue(this.state.somevalue)} /> 
   </div>
  )
 }
}

很简单,我们在父母中使用一个setter来获取相应孩子的状态。

我们将一个值作为参数,并将父状态的状态设置为该值。我已经将它命名为childstate,因此很清楚我们发送给父母的任何价值来自孩子。

getFromChild = (value) => this.setState({childstate:value})

将该功能作为道具从Child1传递到Child2

<Child2 getFromChild={props.getFromChild}/>

Child2中添加onClick处理程序,将值从子级发送到Parent

<button onClick={() => this.sendValue(this.state.somevalue)} />

相关问题