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

17

我可以解释我正在尝试做什么,但是这个ReactJS示例正好讲解了我想要的内容。问题是我无法弄清楚React Native的等效方法。

基本上,当我在TextInput中按返回键时,我希望文本被清除并保持焦点。

您有什么想法吗?

3个回答

32

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中),将其切换回默认值(空)并保持元素的焦点。


这只有一半的时间有效。增加超时时间可以帮助,但必须有一个始终有效的解决方案。 - brysgo
使用软键盘更可靠,但是键盘会跳出关闭再打开。 - brysgo
1
onSubmitEditing 上怎么做呢? - Jarrod Mosen

0

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

... 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/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接