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

时间:2017-01-24 11:07:36

标签: javascript reactjs react-native

如何根据 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]

2 个答案:

答案 0 :(得分:5)

您错放了}

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

答案 1 :(得分: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>
  );
}
相关问题