use*_*867 37 javascript reactjs react-native
我需要更改渲染函数并在给定特定状态时运行一些子渲染函数,
例如:
render() {
return (
<View style={styles.container}>
if (this.state == 'news'){
return (
<Text>data</Text>
)
}
</View>
)
}
Run Code Online (Sandbox Code Playgroud)
如何在不改变场景的情况下实现它,我将使用选项卡动态更改内容.
May*_*kla 78
根据DOC:
if-else语句在JSX中不起作用.这是因为JSX只是函数调用和对象构造的语法糖.
基本规则:
JSX基本上是语法糖.编译之后,JSX表达式成为常规JavaScript函数调用并评估为JavaScript对象.我们可以通过将它包装在花括号中来在JSX中嵌入任何JavaScript表达式.
但只有表达式而不是语句,意味着我们不能在JSX中放任何语句(if-else/switch/for).
如果要有条件地渲染元素,请使用ternary operator,如下所示:
render() {
return (
<View style={styles.container}>
{this.state.value == 'news'? <Text>data</Text>: null }
</View>
)
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是,调用函数jsx并将所有if-else逻辑放在其中,如下所示:
renderElement(){
if(this.state.value == 'news')
return <Text>data</Text>;
return null;
}
render() {
return (
<View style={styles.container}>
{ this.renderElement() }
</View>
)
}
Run Code Online (Sandbox Code Playgroud)
Yus*_*bek 30
您可以通过使用立即调用函数表达式 (IIFE) 来实现您所说的
render() {
return (
<View style={styles.container}>
{(() => {
if (this.state == 'news'){
return (
<Text>data</Text>
)
}
return null;
})()}
</View>
)
}
Run Code Online (Sandbox Code Playgroud)
这是工作示例:
但是,就您而言,您可以坚持使用三元运算符
soo*_*per 10
我发现这种方式是最好的:
{this.state.yourVariable === 'news' && <Text>{data}<Text/>}
Run Code Online (Sandbox Code Playgroud)
我喜欢这个,它的工作正常.
constructor() {
super();
this.state ={
status:true
}
}
render() {
return(
{ this.state.status === true ?
<TouchableHighlight onPress={()=>this.hideView()}>
<View style={styles.optionView}>
<Text>Ok Fine :)</Text>
</View>
</TouchableHighlight>
:
<Text>Ok Fine.</Text>
}
);
}
hideView(){
this.setState({
home:!this.state.status
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67872 次 |
| 最近记录: |