How do i load my React component conditionally?

萝らか妹 提交于 2019-12-23 02:04:28

问题


How do i load my React toolbar component conditionally on state change?

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

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

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

回答1:


Looks like you got a typo error you added ; after null this is unneeded also you can get rid of the getToolbar function Instead try:

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

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



回答2:


Another way to render something conditionally is to do this:

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

Which of course due to how 'truthiness' works in javascript, means you could shorten that further to this:

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


来源:https://stackoverflow.com/questions/38615767/how-do-i-load-my-react-component-conditionally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!