我使用反应导航 TabNavigator,我希望每次用户转到第二个选项卡时,屏幕中的一个文本输入获得焦点并弹出键盘
您可以使用 refs 和 react 导航生命周期:
constructor(props) {
super(props);
this.input = React.createRef();
this.didFocusDSubscription = this.props.navigation.addListener(
'didFocus',
payload => {
this.input.current.focus();
}
);
}
render() {
return <TextInput ref={this.input} />;
}
对您有所帮助
this.viewDidAppearListener = this.props.navigation.addListener('didFocus', (payload) => this._viewDidAppear(payload));
每次显示视图时都会触发didFocus
事件(如 iOS 中的viewDidAppear
),因此您可以手动对文本输入执行focus()
。
最简单的方法是在文本输入中添加"自动对焦"喜欢这个:
<TextInput
placeholder="Type any activity name"
placeholderTextColor="lightgray"
...
ref="textInput"
autoFocus />
用于反应navigation@3。X.X 使用 navigation.addListener 和 .focus():
class AutoFocusedTextInput extends React.Component {
state = {
text: '',
}
componentDidMount() {
this.props.navigation.addListener('didFocus', payload => {this.textInput.focus()})
}
componentWillUnmount() {
didFocusSubscription.remove();
}
render() {
return (
<View>
<TextInput
ref={(component) => this.textInput = component}
autoFocus={true}
placeholder="Start typing"
onChangeText={(text) => this.setState({text})}
value={this.state.text}
/>
</View>
)
}
}
参考资料:
https://reactnavigation.org/docs/3.x/navigation-prop#addlistener---subscribe-to-updates-to-navigation-lifecycle