繁体   English   中英

Reactjs:是否可以使用来自另一个Parent的子组件的Parent组件属性

[英]Reactjs:Is it possible to use Parent component property from another Parent's child component

我有一个名为separatefile.jsx的文件,在此文件中父组件名称为Content,子组件名称为Child。

separatefile.jsx

 import React from 'react'; import Parent from './learning.jsx'; class Content extends React.Component { constructor() { super(); this.state = { finding : 'i am finding' } } render() { return ( <div> <Child childprop={this.state.finding}/> <Parent/> </div> ); } } class Child extends React.Component { render() { return ( <div> <h2>{this.props.childprop}</h2> <h1>child class property</h1> </div> ); } } export default Content; 

这是另一个名为learning.jsx的文件,该文件的父组件名为Parent,子组件名为Children。

我的问题是我需要从Child组件(separatefile.jsx文件的子组件)访问Parent组件属性(learning.jsx的父组件)...

learning.jsx

 import React from 'react'; class Parent extends React.Component { constructor() { super(); this.state = { searching : 'i will find the solution' } } render() { return ( <div> <Children childrenprop={this.state.searching}/> </div> ); } } class Children extends React.Component { render() { return ( <div> <h2>{this.props.childrenprop}</h2> </div> ); } } export default Parent; 

这可能不是一个直接的答案,但如果你正在开始一个新的应用程序,我会建议你使用终极版反应,终极版

Redux是JavaScript应用程序的可预测状态容器。

它可以帮助您编写行为一致的应用程序,在不同的环境(客户端,服务器和本机)中运行,并且易于测试。 最重要的是,它提供了出色的开发人员体验,例如实时代码编辑与时间旅行调试器相结合

它是一个非常小的库,因此很容易理解一切是如何工作的。 它可能是您的问题的一个很好的解决方案。

Todo应用程序示例
您还可以查看精彩的egghead.io免费教程 - Redux入门

以下是其作者Dan Abramov 关于redux收益的答案

如果我理解正确,你想在你的Children组件中使用Parent的状态吗?

您可以将其作为props传递给组件树,例如:

class Content extends React.Component {
  constructor() {
    super();
    this.state = {
      finding : 'i am finding'
    }
  }
  render() {
    return (
      <div>
        <Child childprop={this.state.finding}/>
        <Parent finding={this.state.finding} />
      </div>
    );
  }
}

class Parent extends React.Component {
  constructor() {
    super();
    this.state = {
      searching : 'i will find the solution'
    }
  }
  render() {
    return (
      <div>
        <Children finding={this.props.finding} childrenprop={this.state.searching}/>
      </div>
      );
  }
}

class Children extends React.Component {
  render() {
    return (
      <div>
        <h2>{this.props.childrenprop}</h2>
        <div>{this.props.finding}</div>
      </div>
    );
  }
}

React文档提供了答案。

对于没有父子关系的两个组件之间的通信,您可以设置自己的全局事件系统。 订阅componentDidMount()中的事件,取消订阅componentWillUnmount(),并在收到事件时调用setState()。 通量模式是安排这种方式的可能方式之一。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM