【问题标题】:React Native TextInput does not get focusReact Native TextInput 没有获得焦点
【发布时间】:2017-10-12 17:15:50
【问题描述】:

我有一个TextInput 的简单代码,我希望它在首次呈现和提交时获得焦点。但是,它根本没有得到焦点。

render() {
    return (
      <TextInput
        ref={(c) => this._input = c}
        style={[styles.item, this.props.style]}
        placeholder={"New Skill"}
        onChangeText={(text) => {
          this.setState({text})
        }}
        onSubmitEditing={(event) => {
          this.props.onSubmitEditing(this.state.text);
          this._input.clear();
          this._input.focus();
        }}
      />
    );
  }

  componentDidMount() {
    this._input.focus();
  }

【问题讨论】:

  • 是专注还是不专注?
  • 哦,对不起,我的措辞。我希望它集中注意力,但它没有。
  • 把这个 ref={(c) =&gt; this._input = c} 改成 ref={(c) =&gt; { this._input = c }} 看看能不能用
  • 不,它仍然没有得到焦点
  • 您可以尝试将焦点包含在setTimeOut 函数中,例如:setTimeout(() =&gt; this._input.focus(), 250);

标签: react-native


【解决方案1】:

所以我的假设是正确的。尝试对焦失败,this._input 在调用componentDidMount 时不包含任何内容,因为尚未调用render 函数并且没有对其的引用。

所以目前的解决方案是延迟一点,直到渲染函数已经被调用。

这就是为什么将代码包装在setTimeout 函数中非常有用。无论如何,我承认,这有点棘手。如果有人找到更好的方法,那就太好了。

componentDidMount() {
   setTimeout(() => this._input.focus(), 250);
}

【讨论】:

  • 谢谢!您的解决方案是我发现正在工作的唯一解决方案。但是 componentDidMount() 是在 render() 方法之后调用的,所以你的解释是错误的。此外,您可以将超时设置为 0,并且该解决方案仍然有效。我很好奇这种行为背后的原因。
  • 有没有人用 iOS,或者特别是 iOS - Web 测试过这个...我已经尝试过这种方法,它适用于 android 和 android - web,但似乎不适用于 iOS 或 iOS - 网络。
【解决方案2】:

您可以使用 TextInput 的 autoFocus 属性并将其设置为 true。它会自动将 TextInput 集中在 componentDidMount 上。我对其进行了测试,它会将输入集中在 componentDidMount 和 onSubmitEditing 上。

render() {
return (
  <TextInput
    ref={(c) => this._input = c}
    placeholder={"New Skill"}
    autoFocus={true}
    onChangeText={(text) => {
      this.setState({text})
    }}
    onSubmitEditing={() => {
      this.props.onSubmitEditing(this.state.text);
      this._input.clear();
      this._input.focus();
    }}
  />
);
}

【讨论】:

    猜你喜欢
    • 2020-06-06
    • 2020-04-25
    • 2016-03-09
    • 1970-01-01
    • 2022-01-19
    • 2016-11-08
    • 2018-08-07
    • 1970-01-01
    • 2020-05-20
    相关资源
    最近更新 更多