Find element by Node ID

2019-07-27 18:20发布

问题:

I'm in the middle of building a react-native app and running into problems trying to find an element by it's Node ID.

Some context:

I'm using a Form library for my register form that has a handleFormFocus function. This gets triggered anytime any one of the inputs are focused. The parameters provided to that function are the event and the component ID (integer number), neither of which give me any useful information about which input was actually focused (i.e. "email"), but instead leave me with only an ID.

When I was using react-native 0.34 I was able to do the following:

const ReactNativeComponentTree = require('react/lib/ReactNativeComponentTree'); let targetComponent = ReactNativeComponentTree.getInstanceFromNode(component); let inputRef = targetComponent._currentElement.props.fieldRef;

but since updating to 0.41 this no longer works. I get the following error: Unable to resolve module react/lib/ReactNativeComponentTree

Anyone know how to accomplish finding an element by its id with react native 0.41?

Thanks for your time!

回答1:

React 0.41+:

import ReactNativeComponentTree from 'react-native/Libraries/Renderer/src/renderers/native/ReactNativeComponentTree';

React 0.51+:

import ReactNativeComponentTree from 'react-native/Libraries/Renderer/shims/ReactNativeComponentTree';