![](/img/trans.png)
[英]If I return jsx of a Component from some method and call that method in another component's render, then is a new object created on every render?
[英]Return JSX from component method to render method
我還是React的新手。 我正在嘗試在類組件下的另一個方法中定義的條件下呈現jsx,如下所示:
isWinner = () => {
let userVotesCount1 = this.state.user1.userVotesCount;
let userVotesCount2 = this.state.user2.userVotesCount;
if (userVotesCount1 > userVotesCount2) {
userVotesCount1++;
this.setState({ user1: { userVotesCount: userVotesCount1 } });
return (
<h3>Winner</h3>
);
}
userVotesCount2++;
this.setState({ user2: { userVotesCount: userVotesCount2 } });
return (
<h3>Loser</h3>
);}
我在render方法中調用此方法
<Dialog
open={open}
onRequestClose={this.onClose}
>
<div>
<isWinner />
</div>
</Dialog>
已經嘗試對{() => this.isWinner()}
使用replace <isWinner />
,而我從方法中都沒有得到回報。 我做錯了什么? 因為我在這里處理狀態,所以我不知道如何使用外部函數來做到這一點。 由於某種原因,此函數從未被調用過。 請幫忙!
你快到了。 您要做的是使用方法設置一個標志,然后在render方法中使用該標志有條件地進行渲染。
constructor(props) {
...
this.state = {
isWinner: false,
...
}
}
isWinner() {
...,
const isWinner = __predicate__ ? true : false;
this.setState({
isWinner: isWinner
});
}
render() {
const { isWinner } = this.state;
return isWinner ? (
// jsx to return for winners
) : (
// jsx to return for lossers
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.