我知道如何通过更改状态来添加和删除单个组件。但如果您有多个组件需要删除,这种方法就行不通了。例如,假设我有 3 个视图。当我点击它们时如何删除它们。
示例代码:
class Example extends Component {
render(){
return (
<View>
<View>
<TouchAbleOpacity onPress={() => this.removeView()}>
<Text>Remove View 1</Text>
</TouchAbleOpacity>
</View>
<View>
<TouchAbleOpacity onPress={() => this.removeView()}>
<Text>Remove View 2</Text>
</TouchAbleOpacity>
</View>
<View>
<TouchAbleOpacity onPress={() => this.removeView()}>
<Text>Remove View 3</Text>
</TouchAbleOpacity>
</View>
</View>
)
}
removeView(){
}
}
另一个例子是当我有一个带有按钮的 ListView 时。这些是邀请用户的按钮。当我单击按钮时,我想隐藏 ListView 中该特定行的按钮。
有什么建议么?
感谢 Giorgos,我找到了自己问题的解决方案。我创建了一个单独的组件,该组件内部有一个隐藏函数。现在我可以将此组件添加到视图或列表视图中的任何位置,当我单击它时它就会隐藏。请记住,这仅隐藏组件并且不会卸载它。
这只是一个示例,因此我创建了一个按钮组件。
我的按钮组件:
class ButtonComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
hide:false
}
}
render() {
return (
<View style={styles.container}>
{this.renderButtonComponent()}
</View>
);
}
renderButtonComponent(){
if(!this.state.hide){
return (
<TouchableOpacity onPress={this.hide.bind(this)}>
<Text>Button</Text>
</TouchableOpacity>
);
}
}
hide(){
this.setState({
hide:true
});
}
}
在我的视图中,我只是渲染我的组件:
render() {
return (
<View style={styles.container}>
<ButtonComponent/>
<ButtonComponent/>
<ButtonComponent/>
</View>
);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)