提交后如何获得 React Native TextInput 以保持焦点?

How do I get a React Native TextInput to maintain focus after submit?

我可以解释我想做什么,但 this ReactJS example 是我想要的东西的演练。问题是我不知道 React Native 的等价物是什么。

基本上,当我在 TextInput 中按下 return 时,我希望清除文本并保持焦点。

有什么想法吗?

我提出了以下(可行的)解决方案:

var NameInput = React.createClass({
  getInitialState() {
    return {
      textValue: ''
    }
  },

  clearAndRetainFocus: function(evt, elem) {
    this.setState({textValue: elem.text});
    setTimeout(function() {
      this.setState({textValue: this.getInitialState().textValue});
      this.refs.Name.focus();
    }.bind(this), 0);
  },

  render() {
    return(
      <TextInput
        ref='Name'
        value={this.state.textValue}
        onEndEditing={this.clearAndRetainFocus} />
    )
  }
});

所以,基本上当我们结束编辑时,我们会将 textValue 状态设置为 TextInput 的值,紧接着(在 setTimeout 中),我们将其切换回来默认(空)并保持对元素的关注。

我已经提交了一个 blurOnSubmit 属性 的 PR。

将其设置为 false 并且 TextInput 永远不会模糊,但 onSubmitEditing 仍然会触发。

希望它被合并。 :)

https://github.com/facebook/react-native/pull/2149

我不知道如何触发 blurOnSubmit,但如果你这样做了并且它有效,你应该这样做。我发现在我正在制作的聊天应用程序中使用功能性反应组件的另一件事是:

... import statments

const ChatInput = props => {
const textIn = React.useRef(null) //declare ref
useEffect(()=>textIn.current.focus()) //use effect to focus after it is updated

const textInputChanged = (text) =>{
    props.contentChanged(text);
}

const submitChat = () =>{
    const txt = props.content.trim()
    txt.length >0 ?  props.sendChat(txt, props.username) : null;
}

const keyPressEvent = (e) =>{
   return e.key == 'Enter'? submitChat() : null;
}

return (
     
        <TextInput 
        style={styles.textInput}
        keyboardType={props.keyboardType}
        autoCapitalize={props.autoCapitalize}
        autoCorrect={props.autoCorrect}
        secureTextEntry={props.secureTextEntry}
        value={props.content}
        onChangeText={textInputChanged}  
        onKeyPress={keyPressEvent}
        autoFocus={true}  //i don't think you need this since we are using useEffect
        ref={textIn} //make it so this is the ref
    />
   )}
... export default react-redux connect stuff

如果您有更多输入,您可能可以在 useEffect 挂钩中执行某种引用选择逻辑

这是帮助我弄清楚的文章,几乎是一回事: https://howtocreateapps.com/how-to-set-focus-on-an-input-element-in-react-using-hooks/