簡體   English   中英

如何在 React class 組件的屬性中訪問 state?

[英]How to access state within a property of a React class component?

我有一個 React Class 組件,我想從中分離出渲染的 JSX 的一部分,但我似乎無法在分離的 JSX 中獲得組件的 state(作為類的屬性)。

實際情況和這個例子很相似

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      x: 1
    };
  }

  button = (
    <button onClick={() => this.setState({ x: 2 })}>{this.state.x}</button>
  );

  render() {
    return (
      <>
        x = {this.state.x}
        <button onClick={() => this.setState({ x: 2 })}>{this.state.x}</button> // this works!
        {this.button} // this doesn't :(
      </>
    );
  }
}

現在,當我嘗試直接在 render() 方法中讀取this.state.x時,它按預期工作,但是當我將代碼放在button屬性中並通過調用this.button將其注入到 render() 方法中時括號然后this.state未定義,我無法讀取 state。

我嘗試使用像getX = () => this.state.x這樣的實用方法,並在button屬性中調用它,但它沒有得到 state。

我還嘗試設置另一個屬性_this = this並在括號內調用this._this.getX 這也沒有用。

關於如何讓它工作的任何想法? 任何幫助表示贊賞!

使用箭頭 function 您將獲得組件實例的隱式引用:

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      x: 1
    };
  }

  renderButton = () => (
    <button onClick={() => this.setState({ x: 2 })}>{this.state.x}</button>
  );

  render() {
    return (
      <>
        x = {this.state.x}
        <button onClick={() => this.setState({ x: 2 })}>{this.state.x}</button>
        {this.renderButton()}
      </>
    );
  }
}

使用 function 語法,您需要在構造函數中綁定this

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      x: 1
    };
    renderButton = renderButton.bind(this);
  }

  renderButton() {
    return <button onClick={() => this.setState({ x: 2 })}>{this.state.x}</button>
  };

  render() {
    return (
      <>
        x = {this.state.x}
        <button onClick={() => this.setState({ x: 2 })}>{this.state.x}</button>
        {this.renderButton()}
      </>
    );
  }
}

暫無
暫無

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

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