在反应中从父组件访问子组件的子状态 [英] Access child state of child from parent component in react

查看:46
本文介绍了在反应中从父组件访问子组件的子状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从父组件访问 状态.

I want to access <Child2> state from parent component.

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

如何实现?

推荐答案

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

You shouldn't do this at all. In react information should always flow from top to bottom. The react way to do this is to lift state up to the parent and pass values down as props. In your child you have callbacks that get also passed as props that the child calls, when values change (e.g. through user interaction) so that the parent can update its state:

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} />;
  }
}

codesandbox 工作示例

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

This can be done infinitely deeply nested. In a bigger application where your state needs to be used in multiple components spread all over your component tree you may reach a point where this gets a PITA. The common way to overcome this is to use a global store like redux provides.

这篇关于在反应中从父组件访问子组件的子状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆