[英]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.