根据React Native中的条件渲染元素

问题描述 投票:2回答:2

如何根据React Native中的条件渲染元素?

这是我尝试的方式:

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>
  );
}

但是会出现此错误消息:

Expected a component class, got [object Object]
javascript reactjs react-native
2个回答
5
投票

你错放了你的}

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

3
投票

请记住,您必须将所有内容都包装在视图中。

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>
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.