我有一个按钮,当它被按下时,我希望它打开键盘并专注于文本输入组件。
对于一个最小的代码示例,我正在尝试做的是这个-
<View>
<AddSomething
textChange={textInput => this.setState({ textInput })}
addNewItem={this.addItem.bind(this)}
textInput={this.state.textInput}
ref={not sure what goes here} //passing these as props to a text input
/>
<FloatingButton tapToAddHandler={this.onFloatingButtonPress.bind(this)} />
</View>
然后是我处理按钮按下的一些辅助函数 (this.onFloatingButtonPress)
最佳答案
首先声明你的 AddSomething
如下:
const AddSomething = React.forwardRef((props, ref) => (
<TextInput
ref={ref}
//your other code
/>
));
现在您可以使用 ref
并能够如下所示聚焦您的 AddSomething
组件:
<View>
<AddSomething
textChange={textInput => this.setState({ textInput })}
addNewItem={this.addItem.bind(this)}
textInput={this.state.textInput}
ref={(ref) => { this.textInputField = ref }}
/>
<FloatingButton tapToAddHandler={this.onFloatingButtonPress.bind(this)} />
</View>
这是您的onFloatingButtonPress
方法:
onFloatingButtonPress() {
this.textInputField.focus();
}
关于react-native - 如何在 React Native 中按下按钮打开键盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58241596/