在这里,我persons在App类内部创建了一个局部变量,然后JSX根据某种条件为其分配了a ,然后{persons}在render()方法内部传递了它。
persons
App
JSX
{persons}
render()
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.
let showPersons = null;
let
[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.
逻辑表达式从左到右求值时,将使用以下规则测试它们的可能的“短路”评估:
false && (anything) is short-circuit evaluated to false.
true || (anything) is short-circuit evaluated to true.
在您的应用中,这意味着:
this.state.showPerson
false && JSX = false
true && JSX = true
另外,您也可以使用三元表达式:
condition ? expr1 : expr2 如果condition为true,则运算符返回expr1; 的值。否则,它返回的值expr2
condition ? expr1 : expr2
如果condition为true,则运算符返回expr1; 的值。否则,它返回的值expr2
condition
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} );
但是我个人更喜欢前一种解决方案。