繁体   English   中英

React-native:有条件地在渲染(返回)中显示文本

[英]React-native: Show Text in Render (return) with conditional

如果某些值的变量,我试图向用户显示一些消息。

我有一个这样的代码:

connection(device, side) {
//....
if(side == "right"){
this.setState({deviceRight: true})
}
}

renderConnection(connectionProgress){
  switch(connectionProgress) {
  case 1: 
    if(this.state.deviceRight == true){
     return(<View><Text>Device Right Connected</Text></View>)
}
  default: 
   return null;
}

render() {

 const {connectionProgress} = this.state
 return (
     <Text>Waiting for connection..</Text>
     {this.renderConnection(connectionProgress)}
)
}
}

所以我会在变量(例如deviceRight设置为“true”)时显示文本。

我能怎么做?

我是这样解决的:

connection(device, side) {
//....
if(side == "right"){
this.setState({deviceRight: true})
}
}

renderConnection(){
  if(this.state.deviceRight == true)
     {
      return <Text>Device Connected </Text>
     }
 else {
   return <Text> Device not Connected</Text>}
}

render() {
 return (
     <Text>Waiting for connection..</Text>
     {this.renderConnection()}
)
}
}

在这种情况下,您可以使用三元运算符,如下所示 -

render() {
 return (
   <View>
     <Text>Waiting for connection..</Text>
     {this.state.deviceRight ? (
       <Text>Device Connected </Text>
     ) : (
     <Text> Device not Connected</Text>
     )}
   </View>
  )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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