如何在本地按下按钮时打开键盘?

时间:2019-10-04 18:34:24

标签: react-native expo

我有一个按钮,当我按下按钮时,我想打开键盘并专注于文本输入组件。

对于一个最小的代码示例,我想要做的就是这个-

      <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)

2 个答案:

答案 0 :(得分:1)

首先如下声明您的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();
} 

答案 1 :(得分:0)

提议一个react-hook版本:

const inputRef = React.useRef()

return (
  <TextInput ref={inputRef} />
  <TouchableOpacity onPress={() => inputRef.current.focus()}>
    <Text>Press</Text>
  </TouchableOpacity>
)
相关问题