【问题标题】:How can I findViewById() in react-native android如何在 react-native android 中找到 ViewById()
【发布时间】:2015-11-26 10:45:20
【问题描述】:

我在我的 index.android.js 文件中指的是这个..

<View>
  <CustomView>
    ...
  </CustomView>
</View>

【问题讨论】:

    标签: android reactjs react-native


    【解决方案1】:

    这可以通过React.findNodeHandle完成。

    在你的情况下,

    ...
    
    var { findNodeHandle } = React;
    
    ...
    
    render: function() {
      return (
        <View>
          <CustomView ref="customView">
            ...
          </CustomView>
        </View>
      );
    },
    
    somethingLikeComponentDidMount: function() {
      var customViewNativeID = findNodeHandle(this.refs.customView);
      // Something else...
    }
    
    ...
    

    可能会做这项工作。

    对于一个工作示例(本机绑定两个组件),请查看 here 作为 JS 部分和 here 作为本机 Java 部分。

    【讨论】:

    • 这段代码对我不起作用。我收到错误“TypeError:_react.default.findNodeHandle 不是函数”
    【解决方案2】:

    为组件使用 refs,它可以作为组件的引用

    例如:

    <View>
    <TextInput style={styles.textInput}
               ref={'usrname'}
               placeholder={'Username'}
               placeholderTextColor={'red'}
               onChangeText={(userName) => this.setState({userName})}
               value={this.state.userName} />
    <TouchableOpacity onPress={this._onPressButton}>
                  <View style={styles.buttonContainer}>
                    <Text> Submit </Text>
                  </View>
                </TouchableOpacity>
    </View>
    

    和 onPress:

    _onPressButton: function(e){
        var x = this.state.userName;
        alert(x); //we can also use alert(this.state.userName)
      },
    

    【讨论】:

    • 谢谢... @Pramod Mg 但我如何在我的 java 代码中使用它?我可以将它传递给我的模块吗?像 Mymodule._module.func(x);
    • 因为我想在我的 java 中使用我的 CustomView,比如.. View canvasView = findViewById(R.id.CustomView);所以我可以捕获我的 CustomView 中的任何内容,问题是 react-native 没有 xml,我知道如果它有一个 xml 文件我可以说很容易.. findViewById()...
    猜你喜欢
    • 1970-01-01
    • 2022-07-24
    • 1970-01-01
    • 2015-06-22
    • 2022-08-02
    • 2019-05-10
    • 1970-01-01
    • 2018-03-16
    • 2017-02-02
    相关资源
    最近更新 更多