这里我创建一个局部变量persons
在 - 的里面App
类然后分配一个JSX
根据某些条件传递给它,然后传递它({persons}
) 里面render()
method.
let persons = null;
if (this.state.showPerson) {
persons = (
<div>
<RenderPerson
name={this.state.customers[0].name}
age={this.state.customers[0].age} />
<RenderPerson
name={this.state.agents[1].name}
age={this.state.agents[1].age} />
</div>
);
}
我收到编译错误let showPersons = null;
。在 VS 代码中,如果我将鼠标悬停在红色标记线上let
它说的关键字:[js] Unexpected token. A constructor, method, accessor, or property was expected.
你可以按照卡洛在他的帖子中建议的去做。但是,您可能不需要persons
根本没有变量。因此,如果您在应用程序的其他地方不需要该变量,请考虑以下解决方案:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
showPerson: false
}
}
render() {
return (
{this.state.showPerson && <div>
<RenderPerson
name={this.state.customers[0].name}
age={this.state.customers[0].age}
/>
<RenderPerson
name={this.state.agents[1].name}
age={this.state.agents[1].age}
/>
</div>}
);
}
}
上面的语法称为短路评估:
由于逻辑表达式是从左到右计算的,因此使用以下规则测试可能的“短路”计算:
false && (anything) is short-circuit evaluated to false.
true || (anything) is short-circuit evaluated to true.
在您的应用程序中,这意味着:
- If
this.state.showPerson
是假的,那么false && JSX = false
,什么也不渲染。
- If
this.state.showPerson
是真的,那么true && JSX = true
,它会呈现您的 JSX。
或者,您也可以使用三元表达式:
condition ? expr1 : expr2
If condition
为 true 时,运算符返回的值expr1
;否则,它返回的值expr2
在您的应用程序中将是:
return (
{this.state.showPerson ? <div>
<RenderPerson
name={this.state.customers[0].name}
age={this.state.customers[0].age}
/>
<RenderPerson
name={this.state.agents[1].name}
age={this.state.agents[1].age}
/>
</div> : null}
);
但我个人更喜欢前一种解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)