React Native TextInput无法获得焦点

14

我有一段简单的代码,使用了一个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();
  }

它是获取焦点还是失去焦点? - bennygenel
哦,抱歉我的措辞有误。我想让它变得更加专注,但却没有做到。 - bleepmeh
1
将此代码 ref={(c) => this._input = c} 更改为 ref={(c) => { this._input = c }},然后查看是否有效。 - bennygenel
仍然没有获得焦点。 - bleepmeh
1
你能否尝试将焦点包裹在setTimeout函数内,如下: setTimeout(() => this._input.focus(), 250); - I Putu Yoga Permana
显示剩余2条评论
3个回答

21

所以我的假设是正确的。尝试集中注意力失败了,this._inputcomponentDidMount被调用时不包含任何内容,因为render函数还没有被调用,也没有对它的引用。

现在的解决方法是稍微延迟一下,直到渲染函数已经被调用。

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

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

2
谢谢!你的解决方案是我找到的唯一可行的。但是componentDidMount()方法在render()方法之后被调用,所以你的解释是错误的。此外,你可以将超时设置为0,这个解决方案仍然有效。我对这种行为背后的原因非常好奇。 - Michael Wallace
有人已经在iOS或者特别是iOS-Web上测试过这个吗?我已经尝试了这种方法,对于安卓和安卓-Web来说效果非常好,但是似乎在iOS或者iOS-Web上不起作用。 - Kyle Rohlfing

2
您可以使用TextInput的autoFocus属性,并将其设置为true。它会在componentDidMount上自动聚焦TextInput。我测试过,它会在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();
    }}
  />
);
}

0
添加这个
  const inputRef: LegacyRef<TextInput> = useRef(null);
  useEffect(() => {
    if (inputRef.current) {
      setTimeout(() => {
        inputRef.current?.focus();
      }, 0);
    }
  });

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