我有一个像这样的渲染函数:
render() {
const statement = true
return (
<div>
{
statement &&
<div>
<p>
{this.buildStuff()}
</p>
<p>
{this.buildStuff()}
</p>
<p>
{this.buildStuff()}
</p>
</div>
}
</div>
);
}
为了避免调用 buildStuff()
三次,我想将其分配给一个变量。如何在带有 statement &&
的行之后声明变量?
一个快速的解决方案是这样做
const statement = true
const stuff = statement ? buildStuff() : null;
但是这个解决方案使用两个分支而不是一个。
您可以在 StackBlitz 上尝试此代码.
这就是 Razor 中的样子.
最佳答案
你也可以尝试这样的事情:
- 您可以创建一个处理此 UI 表示的函数。
- 在此函数中,您可以调用
buildStuff
并让它返回 3<p>
标签。 - 然后在主渲染中,您可以检查您的条件并进行相应的渲染。这将使您的渲染变得干净且具有声明性。
getBuildJSX() {
const stuff = this.buildStuff();
return Array.from({ length: 3}, () => <p> { stuff }</p>);
}
render() {
const statement = true
return (
<div>
{
statement ? this.getBuilsJSX() : null
}
</div>
);
}
关于javascript - 如何在括号内声明变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54214406/