如何通过节点ID获得真正的元素?反应母语

Cod*_*Lim 12 react-native

<TouchableHighlight onPress={this._onPress.bind(this)}>
  <Text style={{color: 'white'}}>CLOSE</Text>
</TouchableHighlight>

_onPress(e) {
  console.log(e.nativeEvent.target);
}
Run Code Online (Sandbox Code Playgroud)

如上所述,这target只是一个名为node id的数字,但我想得到真正的元素.我怎样才能做到这一点?

Mik*_*ski 11

当React/React Native公共代码被移动时,最近更改的代码发生了变化,但我建议的是检查Inspector代码可用的方法.ReactNativeComponentTree

更具体地说,以下代码应该为您解决问题:

var ReactNativeComponentTree = require('react/lib/ReactNativeComponentTree');
ReactNativeComponentTree.getInstanceFromNode(nativeTag);
Run Code Online (Sandbox Code Playgroud)

  • 这始终是一个私有API,并且不再适用于最新的RN版本。 (2认同)

Sun*_*tel 7

这就是我最终为自己解决类似情况的方式.它不会采用任何方式采用相同的方法,但它是诀窍!

onItemPressed(item) {
  this.props.navigateForward(item.sceneId);
  this.props.closeDrawer();
}

render() {
  var listItems = [];

  for (var i=0; i < this.props.navigation.scenes.length; i++) {
    var item = this.props.navigation.scenes[i];

    listItems.push(<ListItem
      onPress={this.onItemPressed.bind(this, item)}
      key={i}
      title={item.title}
      leftIcon={{name: item.icon}}
      underlayColor={colors.lightPrimary}
      containerStyle={styles.menuItemStyle}
      titleStyle={styles.menuItemTitle}
    />);
  }


  return (
    <View style={styles.container}>
      <List containerStyle={styles.listContainer}>
        {listItems}
      </List>
    </View>
  )
};
Run Code Online (Sandbox Code Playgroud)

  • 这种方法以前是可以接受的,但现在的惯例是避免为每个渲染周期传递新创建的函数,因为由于关闭和由于引用每次都不同(因此触发渲染)而导致高性能成本. (4认同)

Yos*_*ger 5

万一有人偶然发现这个问题,ReactNativeComponentTree已从 0.56 版左右删除。

但是,我找到了一种更简洁的方法来检测某个(子)元素上的点击:

import React from 'React';
import {
  Text,
  TouchableOpacity,
  View,

  findNodeHandle
} from 'react-native';

class TestClass extends React.Component {
  onTap = (evt) => {
    // Retrieve the handle of the second <Text> node
    let elementHandle = findNodeHandle(this.refs["element"]);

    // Check if the tapped element's node-id equals the retrieved one 
    if (evt.nativeEvent.target == elementHandle) {
      // Do something when element was clicked
      console.log("Second <Text> node was tapped")
    }
  }

  render() {
    return (
      <TouchableOpacity onPress={this.onTap}>
        <View>
          <Text>Hi there!</Text>
          <Text ref="element">Only detect this element</Text>
        </View>
      </TouchableOpacity>
    );
  }
};
Run Code Online (Sandbox Code Playgroud)

基本上,我们只是使用引用 ( ref) 来使用findNodeHandle.

然后我们将该节点 ID 与nativeEvent.target节点 ID进行比较,以检查子元素是否被挖掘。

在上面的例子中,只有第二个<Text>节点产生输出。