[英]'this' is undefined in React component function
當我嘗試執行以下代碼時,函數renderContents
的this
值是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>
);
}
}
您在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.