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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29420251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:30:47  来源:igfitidea点击:

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

javascriptiosfacebookreactjsreact-native

提问by brysgo

I could explain what I am trying to do, but this ReactJS exampleis a walkthrough of exactly what I want. The problem is I can't figure out what the equivelant would be for react native.

我可以解释我想要做什么,但是这个 ReactJS 示例正是我想要的演练。问题是我无法弄清楚 react native 的等效项是什么。

Basically, when I press return in the TextInput, I want the text cleared and focus maintained.

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

Any thoughts?

有什么想法吗?

回答by Dave Sibiski

I've submitted a PR with a blurOnSubmitproperty.

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

Set it to falseand the TextInputnever blurs, onSubmitEditingstill fires though.

将其设置falseTextInput永不模糊,onSubmitEditing但仍然会触发。

Hopefully it gets merged. :)

希望它合并。:)

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

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

回答by Samuli Hakoniemi

I came out with following (working) solution:

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

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} />
    )
  }
});

So, basically when we end editing, we will set the textValuestate to the value of the TextInputand right after that (in setTimeout), we switch it back to default (empty) and retain focus on the element.

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