簡體   English   中英

我可以在ReactJs中修改組件的父狀態嗎?

[英]Can I modify a parent state of a component in ReactJs?

假設我具有以下組件:

class LeftPanel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {abc: 'xyz'};
  }
render() {
  return (
    <div>
     <Thumb src={img1}/>
     <Thumb src={img2}/>
   </div>);
 }

在組件內部,有一個內部組件,稱為Thumb ,其內容如下:

class Thumb extends React.Component {
  constructor(props) {
   super(props);
   this.state = { src: props.src };
  }

  render() {
   return (
    <div>
      <img src={this.state.src}></img>
    </div>
   );
  }

}

問題:我可以修改Thumb LeftPanel組件的狀態嗎? 如果是,怎么辦?

在“左側”面板中創建一個方法來處理事件。 然后將方法傳遞給子組件。

現在,如果您想將數據傳遞給父級,我會推薦一個類似flux或redux的庫。 由於redux具有全局狀態,因此所有組件均可訪問。 當您修改全局狀態為整個應用程序時,將使用新狀態重新呈現。 所有組件都可以看到新狀態。

class LeftPanel extends React.Component {
  constructor(props) {
    super(props);
    this.modifyLeftpanel = this.modifyLeftpanel.bind(this);
    this.state = {abc: 'xyz'};
  }

  modifyLeftpanel(newvar){
      //Do something with newvar
  }
render() {
  return (
    <div>
     <Thumb src={img1} modifyLeftPanel={this.modifyLeftpanel}  />
     <Thumb src={img2} modifyLeftPanel={this.modifyLeftpanel} />
   </div>);
 }

這是拇指

class Thumb extends React.Component {
  constructor(props) {
   super(props);
   this.state = { src: props.src };
   this.doSomething = this.doSomething.bind(this);
  }

  doSomething(){
       this.props.modifyLeftpanel(10);
  }

  render() {
   return (
    <div>
      <img src={this.state.src}></img>
      <button onClick={this.doSomething}>Modify Parent</button>
    </div>
   );
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM