【问题标题】:How do i load my React component conditionally?如何有条件地加载我的 React 组件?
【发布时间】:2016-12-01 15:07:00
【问题描述】:

如何根据状态更改有条件地加载我的 React 工具栏组件?

constructor(props) {
        super(props);
        this.state = {
            currentpagenum: 0,
        };
    }

render(){
   return(
       <View>
           {this.state.currentpagenum!==0 ? this.getToolbar(): null;}
       </View>
    );
}

getToolbar(){
      return(
            <ToolbarAndroid />
      );
 }

【问题讨论】:

  • 您遇到的错误是什么
  • 去掉null后面的分号
  • 谢谢

标签: javascript reactjs conditional components


【解决方案1】:

看起来您在null 之后添加了; 的拼写错误,这是不必要的,您也可以摆脱getToolbar function 而是尝试:

constructor(props) {
  super(props);
  this.state = {
      currentpagenum: 0,
  };
}

render() {
  return(
      <View>
          {this.state.currentpagenum !== 0 ? <ToolbarAndroid /> : null}
      </View>
   );
}

【讨论】:

    【解决方案2】:

    另一种有条件地渲染某些东西的方法是这样做:

    render() {
      return(
          <View>
              {this.state.currentpagenum !== 0 && <ToolbarAndroid />}
          </View>
       );
    }
    

    当然,由于“真实性”在 javascript 中的工作方式,这意味着您可以将其进一步缩短:

    render() {
      return(
          <View>
              {this.state.currentpagenum && <ToolbarAndroid />}
          </View>
       );
    }
    

    【讨论】:

      猜你喜欢
      • 2016-08-01
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 1970-01-01
      • 2021-05-26
      相关资源
      最近更新 更多