<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)
这就是我最终为自己解决类似情况的方式.它不会采用任何方式采用相同的方法,但它是诀窍!
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)
万一有人偶然发现这个问题,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>节点产生输出。
| 归档时间: |
|
| 查看次数: |
12127 次 |
| 最近记录: |