如何在React Native中删除或卸载组件?

hui*_*min 16 react-native

我想删除我的React Native代码中的组件,就像JavaScript中的"el.parentNode.removeChild(el)"或Objective-C中的"[view removeFromSuperview]",但我没有在React中看到任何相关的API文档.有什么方法可以做到吗?

pet*_*ter 30

在React Native中或者通常在React中我理解你通常不会通过调用'remove [..]'来删除组件,而是通过更改组件的标记来改变虚拟DOM.

这是一些删除屏幕MapView的示例代码.

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  SwitchIOS,
  MapView,
} = React;

var TestMap = React.createClass({

  getInitialState() {
    return {
      showMap: true,
    };
  },

  render: function() {
    var map = this.state.showMap ? <MapView style={styles.map}/> : null;
    return (
      <View style={styles.container}>
        <Text style={{marginBottom: 10}}>Remove a view in React Native</Text>
        <SwitchIOS
          onValueChange={(value) => this.setState({showMap: value})}
          style={{marginBottom: 10}}
          value={this.state.showMap}
          />
        {map}
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 50,
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  map: {
    height: 200,
    width: 300,
    margin: 10,
    borderWidth: 1,
    borderColor: '#000000',
  },

});

AppRegistry.registerComponent('TestMap', () => TestMap);
Run Code Online (Sandbox Code Playgroud)

相关部分是:

  render: function() {
    var map = this.state.showMap ? <MapView style={styles.map}/> : null;
    return (
      <View style={styles.container}>
        [..]
        {map}
      </View>
    );
  }
Run Code Online (Sandbox Code Playgroud)