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

时间:2015-04-02 18:48:04

标签: javascript ios facebook reactjs react-native

我可以解释一下我想要做什么,但是this ReactJS example正是我想要的一个演练。问题是我无法弄清楚equivelant对原生的反应是什么。

基本上,当我在TextInput中按回车键时,我想清除文本并保持焦点。

有什么想法吗?

3 个答案:

答案 0 :(得分:20)

I've submitted a PR with a blurOnSubmit property.

Set it to false and the TextInput never blurs, onSubmitEditing still fires though.

Hopefully it gets merged. :)

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

答案 1 :(得分:6)

我推出了以下(工作)解决方案:

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之后),我们将其切换回默认值(空)并保持对元素的关注。

答案 2 :(得分:0)

我不知道如何触发 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/