如何在Click事件上获取React Native中的元素属性

Utk*_*Sah 5 react-native

如何在React Native中不使用'this'关键字的情况下访问元素的属性?我有一个与父类本身绑定为“ this”的函数,但我想访问被单击元素的属性。这是代码-

import {Circle} from 'react-native-svg';
export default App extends Component {
  constructor(props) {
  super(props);
  this.state = {activeX: null}
 }

 handleTouch(event) {
   const x = event.target.cx; //How to access "cx" property here?
   this.setState({ activeX: x });
 }

 render() {
   return (
     <Circle cx='10' cy='10' r='5' onPress={this.handleTouch.bind(this)}/>
     <Circle cx='20' cy='20' r='5' onPress={this.handleTouch.bind(this)}/>
   );
 }
}
Run Code Online (Sandbox Code Playgroud)

Utk*_*Sah 1

import ReactNativeComponentTree from'react-native/Libraries/Renderer/src/renderers/native/ReactNativeComponentTree';
Run Code Online (Sandbox Code Playgroud)

并访问属性为-

const x = ReactNativeComponentTree.getInstanceFromNode(event.currentTarget)._currentElement.props.cx;
Run Code Online (Sandbox Code Playgroud)

  • 这看起来很古怪。React 是否在某处记录/推荐/认可了它? (5认同)
  • @hippietrail 它很老套而且**非常慢**。我们最好避免这个提示。 (2认同)