I have a TextInput
in my Component (FirstComponent
). I can call the focus on it from the component by calling the this.refs
. I am also importing and calling another Component (SecondComponent
) which also needs to focus on the TextInput
on a button click.
My First Component:
Import SecondComponent from './SecondComponent';
<View>
<TouchableOpacity
onPress={()=>this.refs.MyBox.focus()}
>
<Text>Open</Text>
</TouchableOpacity>
<SecondComponent />
<TextInput
ref='MyBox'
style={{width: '100%', borderColor: 'gray', borderWidth: 1}}
/>
</View>
The SecondComponent
too has a TouchableOpacity
to call the focus on the TextInput
:
<View>
<TouchableOpacity
onPress={()=>this.refs.MyBox.focus()}
>
<Text>Open</Text>
</TouchableOpacity>
</View>
The SecondComponent is rendered fine but cannot call the focus on the TextInput
since it's not in the SecondComponent. How do I resolve this?
Thanks.
You can either pass the reference to the
TextInput
directly:And then in
SecondComponent
callthis.props.textInput.focus()
, or you can pass in the function that does the focusing and invoke it within the second component:And then in
SecondComponent
: