有条件地react渲染 JSX

IT技术 reactjs ecmascript-6
2021-05-19 03:34:32

在这里,我在类中创建一个局部变量personsApp然后JSX根据某些条件为其分配 a ,然后{persons}render()方法内部传递 it( )

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.

2个回答

你可以按照 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为真,则运算符返回值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