小编典典

有条件地反应渲染JSX

reactjs

在这里,我personsApp类内部创建了一个局部变量,然后JSX根据某种条件为其分配了a
,然后{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.


阅读 284

收藏
2020-07-22

共1个答案

小编典典

您可以执行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}
);

但是我个人更喜欢前一种解决方案。

2020-07-22