簡體   English   中英

在React組件函數中未定義'this'

[英]'this' is undefined in React component function

當我嘗試執行以下代碼時,函數renderContentsthis值是undefined

我曾以為,粗箭頭功能會自動將此綁定。 不是嗎? 如果沒有,如何確保將this傳遞給函數renderContents

代碼示例:

class Box extends React.Component {
  renderContents = () => {
      console.log(this); // undefined
      return (
        <div></div>
        )
  }

   render() {
      const { 
        someValue,
      } = this.props;

      return (
            <div>
              {someValue ? this.renderContents() : null}
            </div>
            );
    }
  }

沒有任何錯誤。 我只是這樣稱呼它:

ReactDOM.render((<Box someValue={true} />), document.getElementById('content'));

我得到的這個值:

在此處輸入圖片說明

所以我認為問題是,您說的不對,您是否設置了someValue

您在renderContent方法中犯了錯誤。 您將其聲明為函數,並且沒有組件上下文。 請嘗試聲明如下方法:

renderContent() {
 ...your code...
}

相反,這是:

renderContent = () => {}

您是否嘗試添加構造函數方法?

constructor(props) {
    super(props)
}

編輯:

除了使用箭頭函數,您可以像這樣在構造函數中綁定上下文:

class Box extends React.Component {
    constructor(props) {
        super(props)

        this.renderContents = this.renderContents.bind(this)
    }

    renderContents() {
        console.log(this);
        return (
            <div></div>
        )
    }

    render() {
       const { 
           someValue,
       } = this.props;

       return (
           <div>
               {someValue ? this.renderContents() : null}
           </div>
       );
    }
}

在react類中,僅隱式綁定了某些方法(render,componentDidMount,componentWillUnmount等),其他方法則必須在構造函數中手動綁定或使用箭頭函數。

暫無
暫無

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

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