【问题标题】:Targeting react native views in JavaScript在 JavaScript 中定位反应原生视图
【发布时间】:2015-12-14 13:11:21
【问题描述】:

有没有一种方法可以在 JavaScript 代码中定位在 react native 中创建的视图,类似于我可以在 JavaScript for web 中执行的操作?即为视图提供 ID,然后调用 document.getElementById

我想要实现的是一种在按钮(TouchableHighlight)点击上切换视图可见性的方法。

【问题讨论】:

    标签: javascript ios react-native


    【解决方案1】:

    有一种方法可以通过refs 在 React Native 中定位视图或组件。 https://facebook.github.io/react/docs/more-about-refs.html.

    但是,在您的情况下,如果您尝试切换视图,则可以通过返回基于状态变量为真或假的视图来实现此目的。比如:

    toggleView() {
      this.setState({
          showView: !this.state.showView
      })
    }
    
    var view = <View><Text>This view is being toggled</Text></View>
    
    <TouchableHighlight onPress={ () => this.toggleView() } >
        <Text>Toggle View</Text>
    </TouchableHighlight>
    
    {this.state.showView && view}
    

    有一个工作项目设置here。完整代码如下。

    https://rnplay.org/apps/puK5UQ

    'use strict';
    
    var React = require('react-native');
    var {
      AppRegistry,
      StyleSheet,
      Text,
      View,
      TouchableHighlight
    } = React;
    
    var SampleApp = React.createClass({
    
      getInitialState() {
            return {
                showView: true
            }
        },
    
      toggleView() {
        this.setState({
            showView: !this.state.showView
        })
      },
    
      render: function() {
    
        var view = <View style={{height:100, backgroundColor: 'red'}}><Text>This view is being toggled</Text></View>
    
        return (
          <View style={styles.container}>
            <TouchableHighlight underlayColor="#efefef" onPress={ () => this.toggleView() } style={{marginTop:60, backgroundColor: '#ededed', height:60, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
                <Text style={{ fontSize:20 }}>Toggle View</Text>
            </TouchableHighlight>
            {this.state.showView && view}
          </View>
        );
      }
    });
    
    var styles = StyleSheet.create({
      container: {
        flex: 1,
    
      },
    });
    
    AppRegistry.registerComponent('SampleApp', () => SampleApp);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多