簡體   English   中英

從子級更改父級的一部分 - React.js

[英]Change part of parent from child - React.js

我知道有類似的問題,但沒有人回答我的問題。 可視化這里的問題就是它的樣子。

在此處輸入圖片說明

好的,所以我有以下問題:單擊 Left 組件后,我想將 Body 更改為 BodyLeftClicked,單擊 Right 組件后,我想將 Body 更改為 BodyRightClicked。

我有這樣的 App 組件:

class App extends React.Component {
    state = { choose: "Left" }; //initialize one body

    render() {
        return (
            <div className="All">
                <div className="head">
                    <Top name={"Left"}/>
                    <Top name={"Right"}/>
                </div>

                <div className="body">
                    {(() => {
                        switch(this.state.choose) {
                            case "Left":
                                 return <BodyLeftClicked choose={this.state.choose}/>;
                            case "Right":
                                return <BodyRightClicked choose={this.state.choose}/>;
                        }
                    })()}

                </div>
            </div>
        );
    }
}

頁面頂部的兩個組件(左組件和右組件)由:

class Top extends React.Component {
    constructor(props) {
        super(props);
        this.state = { name : this.props.name };
        this.onButtonClick = this.onButtonClick.bind(this);
    }

    onButtonClick() {
        //CHANGE THE BODY WHICH IS BEING SHOWN IN APP 
    }

    render() {
        return (
            <div>
                <button className="Button" type="button" onClick={this.onButtonClick}>{this.state.name}</button>
            </div>
        )
    }
}

和身體組件的例子:

class BodyLeftClicked extends React.Component {
constructor(props) {
        super(props);
        this.state = { choose : this.props.choose };
    }
    render() {
        return (
            <div className="BodyLeftClicked">  </div>
        )
    }
}

您基本上希望在 App 類中創建一個方法並將其傳遞給您的 Left/Right 組件。 在方法中使用setState ,它會根據傳遞給它的參數而改變。 它看起來像這樣:

class App extends React.Component {
  state = { choose: "Left" };

  setChoose = position => {
    this.setState({ choose: position });
  }
}

然后把它傳下來:

<Top name="Left" onButtonClick={ this.setChoose } />

並通過單擊處理程序從組件內部調用它:

class Top extends React.Component {
  render() {
    return (
      <div>
        <button className="Button" type="button" onClick={props.onButtonClick}>{this.state.name}</button>
      </div>
    );
  }
}

理想情況下,您會對正確的組件執行相同的操作。

使用鈎子

幾乎相同的事情,但您基本上可以免費使用, useState和獲取 setter 方法:

function App(props) {
  const [choose, setChoose] = useState('Left');

  return (
    <Top name="Left" onButtonClick={ setChoose } />
  );
}

暫無
暫無

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

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