简体   繁体   中英

Render an element based on condition in React Native

How do I render an element based on a condition in React Native ?

This is how I tried:

render() {  
  return (
      <Text>amount is: {this.state.amount}</Text> // it correctly prints amount value
      </Button>
         {this.state.amount} >= 85 ? <button>FIRST</button> :   <button>SECOND</button>
      <Text>some text</Text>
  );
}

But this error message appears:

Expected a component class, got [object Object]

You have misplaced your } :

render() {  
  return (
      <Text>amount is: {this.state.amount}</Text>
      {this.state.amount >= 85 ? <button>FIRST</button> : <button>SECOND</button>}
      <Text>some text</Text>
  );
}

Keep in mind that you have to wrap everything inside a view.

render() {  
  return (
    <View>
      <Text>amount is: {this.state.amount}</Text>
         {this.state.amount >= 85 ? 
           <button>FIRST</button> : <button>SECOND</button> 
         }
      <Text>some text</Text>
    </View>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM