簡體   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