Reactjs:是否可以从另一个Parent's子组件中使用Parent组件属性?

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

本文关键字:组件 Parent 属性 是否 另一个 Reactjs      更新时间:2023-09-26

我有一个名为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。

我的问题是,我需要从子组件(分离文件的子组件)访问父组件属性(父组件学习。jsx)。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;

如果我理解正确的话,您想在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>
    );
  }
}

这可能不是一个直接的答案,但如果你正在开始一个新的应用程序,我建议你使用Redux与react-redux。

Redux是一个可预测的状态容器。

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

这是一个非常小的库,所以很容易理解一切是如何工作的。这也许能很好地解决你的问题。

Todo app示例
你也可以看看awesome egghead。Redux入门教程

以下是作者Dan Abramov对redux好处的回答

React文档提供了一个答案。

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