我还是很新的反应,直到现在我仍然无法理解当用户点击特定按钮时如何删除视图。 例如,假设我有这段代码:
import React, { Component } from 'react'
import { AppRegistry, View, Text, TouchAbleOpacity } from 'react-native'
class Example extends Component {
removeView(){
// what should I do here?
}
render(){
return (
<View>
<View> // View to be removed
<TouchAbleOpacity onPress={() => this.removeView()}>
<Text>Remove View</Text>
</TouchAbleOpacity>
</View>
</View>
)
}
}
AppRegistry.registerComponent('example', () => Example);
如何以编程方式删除View元素?
答案 0 :(得分:4)
尝试这样的事情:
class Example extends Component {
constructor(props) {
super(props);
this.state = {
showView: true,
}
}
removeView(){
this.setState({
showView: false,
});
}
render(){
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center' }}>
{this.state.showView && (
<View style={{backgroundColor: 'red', height: 100, width: 100 }}> // View to be removed
<TouchableHighlight onPress={() => this.removeView()}>
<Text>Remove View</Text>
</TouchableHighlight>
</View>
)}
</View>
)
}
}
答案 1 :(得分:2)
我这样做:
import React, { Component } from 'react'
import { AppRegistry, View, Text, TouchAbleOpacity } from 'react-native'
class Example extends Component {
constructor() {
super();
this.state = {
showView:true
}
}
removeView(){
this.setState({
showView:false
})
}
render(){
return (
<View>
{this.renderView()}
</View>
)
}
renderView(){
if(this.state.showView){
return(
<View>
<TouchAbleOpacity onPress={() => this.removeView()}>
<Text>Remove View</Text>
</TouchAbleOpacity>
</View>
);
}
}
}
AppRegistry.registerComponent('example', () => Example);