我对React Native真的很陌生,我想知道如何隐藏/显示组件。
下面是我的测试用例:
<TextInput
onFocus={this.showCancel()}
onChangeText={(text) => this.doSearch({input: text})} />
<TouchableHighlight
onPress={this.hideCancel()}>
<View>
<Text style={styles.cancelButtonText}>Cancel</Text>
</View>
</TouchableHighlight>
我有一个TextInput组件,我想要的是在输入得到焦点时显示TouchableHighlight,然后在用户按下取消按钮时隐藏TouchableHighlight。
我不知道如何“访问”TouchableHighlight组件,以便隐藏/显示它在我的函数showCancel/ hideccancel中。
此外,我如何从一开始就隐藏按钮?
显示\hide组件的三种方法:
——类组件 : / ------------------------------------------------------------------------------------------------------------
在我使用的所有例子中,如下所示:
.
...
constructor(props) {
super(props);
this.state = {showComponent: true};
}
1. 使用展示道具
<View display={this.state.showComponent ? 'flex' : 'none'} />
2. 使用有风格的显示道具
<View style={{display:this.state.showComponent ? 'flex' : 'none'}} />
3.限制呈现
{
this.state.showComponent &&
<View /> // Or <View> ... </View>
}
——功能组件 :/ ------------------------------------------------------------------------------------------------------------
在我使用的所有例子中,如下所示:
const [showComponent, setShowComponent] = useState(true);
1. 使用展示道具
<View display={showComponent ? 'flex' : 'none'} />
2. 使用有风格的显示道具
<View style={{showComponent ? 'flex' : 'none'}} />
3.限制呈现
{
showComponent &&
<View /> // Or <View> ... </View>
}
大多数时候我是这样做的:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {isHidden: false};
this.onPress = this.onPress.bind(this);
}
onPress() {
this.setState({isHidden: !this.state.isHidden})
}
render() {
return (
<View style={styles.myStyle}>
{this.state.isHidden ? <ToHideAndShowComponent/> : null}
<Button title={this.state.isHidden ? "SHOW" : "HIDE"} onPress={this.onPress} />
</View>
);
}
}
如果你是编程新手,这一行对你来说一定很陌生:
{this.state.isHidden ? <ToHideAndShowComponent/> : null}
这条线等于
if (this.state.isHidden)
{
return ( <ToHideAndShowComponent/> );
}
else
{
return null;
}
但是你不能在JSX内容中编写if/else条件(例如渲染函数的return()部分),所以你必须使用这种符号。
这个小技巧在很多情况下都非常有用,我建议你在开发中使用它,因为你可以快速检查条件。
问候,
编辑:对于更直接的语法,您可以执行{this.state。isHidden && <ToHideAndShowComponent/>}。这里,左操作数在右操作数之前求值,因此如果isHidden为false,则该组件将不显示。