【问题标题】:Access child state of child from parent component in react在反应中从父组件访问子组件的子状态
【发布时间】:2018-09-08 13:46:50
【问题描述】:

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

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

如何实现?

【问题讨论】:

标签: reactjs


【解决方案1】:

避免将 props 传递给多个组件的一种方法是使用 reacts context api。

这允许我们从MyProvider 组件向下访问 100 个子组件的状态,而无需手动将 props 向下传递到 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"));

使用context 可能是您正在寻找的。​​p>

还有另一个实现。

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) =&gt; this.setState({childstate:value})

将函数作为道具从Child1 传递给Child2

&lt;Child2 getFromChild={props.getFromChild}/&gt;

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

&lt;button onClick={() =&gt; this.sendValue(this.state.somevalue)} /&gt;

【讨论】:

    【解决方案2】:

    你根本不应该这样做。在反应中,信息应该总是从上到下流动。执行此操作的反应方式是 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 提供的全局存储。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-29
      • 2019-09-17
      • 1970-01-01
      相关资源
      最近更新 更多