如何删除或卸载 React Native 中的组件? [英] How to remove or unmount a component in React Native?

查看:50
本文介绍了如何删除或卸载 React Native 中的组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to remove a component in my React Native code, just like the "el.parentNode.removeChild(el)" in JavaScript or "[view removeFromSuperview]" in Objective-C, but I didn't see any related API in React documents. Is there any way to make it?

推荐答案

在 React Native 或一般在 React 中,据我所知,您通常不会通过调用 'remove[..]' 来删除组件,而是通过更改组件从而改变虚拟 DOM.

In React Native or generally in React as I understand you normally don't remove components by calling 'remove[..]' but by changing the markup of the component thus changing the virtual DOM.

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

Here's some sample code that removes a MapView of a screen.

'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);

相关部分是:

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

这篇关于如何删除或卸载 React Native 中的组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆