![](/img/trans.png)
[英]React Native: Can you conditionally render JSX based on the existence of a string?
[英]react conditionally render JSX
这里我在App
类中创建一个局部变量persons
,然后根据某些条件为它分配一个JSX
,然后在render()
方法中传递它( {persons}
)。
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;
遇到编译错误let showPersons = null;
。 在VS代码中,如果我将鼠标悬停在let
关键字的红色标记行上,则会显示: [js] Unexpected token. A constructor, method, accessor, or property was expected.
[js] Unexpected token. A constructor, method, accessor, or property was expected.
你可以做Carlo在他的帖子中建议的内容。 但是,您可能根本不需要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.
在您的应用中,这意味着:
this.state.showPerson
为false,则false && JSX = false
,它不呈现任何内容。 this.state.showPerson
为true,则true && JSX = true
,这将呈现您的JSX。 或者,您也可以使用三元表达式 :
condition ? expr1 : expr2
如果
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}
);
但我个人更喜欢以前的解决方案。
你可能正在做这样的事情
class App extends React.Component {
// ...
let persons = null;
// ...
}
而你应该这样做
class App extends React.Component {
constructor(props) {
super(props);
this.persons = null;
}
}
在https://babeljs.io/learn-es2015/#classes中查看有关类语法的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.