我知道如何通过更改状态来添加和删除单个组件。但是,如果要删除多个组件,这种方法将行不通。例如,假设我有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,我为自己的问题找到了解决方案。我创建了一个单独的组件,该组件内部具有hide函数。现在,我可以只在视图或listView中的任何位置添加此组件,当我单击它时它将隐藏。请记住,这只会隐藏组件,而不会卸载它。
这只是一个示例,所以我创建了一个按钮组件。
我的按钮组件:
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> ); }