如何在 React Native 中删除视图

Ale*_*lex 4 android reactjs react-native

我仍然很陌生,直到现在我仍然无法理解当用户单击特定按钮时如何删除视图。例如,假设我有以下代码块:

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);
Run Code Online (Sandbox Code Playgroud)

如何以编程方式删除 View 元素?

小智 5

尝试这样的事情:

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>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)