【问题标题】:How to set focus or cursor on TextInput in react native如何在本机反应中在 TextInput 上设置焦点或光标
【发布时间】:2017-08-22 08:04:45
【问题描述】:

我正在使用 react native 的 TextInput 组件。我想在 onPress 函数中设置焦点。

<TextInput
  ref="messageTextInput"
  style={{
    height: 40,
    width: "100%",
    borderColor: "gray",
    borderWidth: 1,
    marginTop: 8
  }}
  underlineColorAndroid="transparent"
  placeholder={strings.enter_your_message}
  onChangeText={text => this.setState({ text })}
/>

_onPress(navigate) {
  try {
    if (!this.state.text.trim()) {
      Alert.alert(strings.app_name, strings.validate_text);
      this.messageTextInput.focus();
    }
  } catch (error) {
    console.log(error);
  }
}

它不会在 messageTextInput 上设置焦点或光标。有谁知道如何在本机反应中做到这一点?

【问题讨论】:

  • onFocus?:文本输入聚焦时调用的函数回调,可以搜索“聚焦”documentation

标签: android ios react-native


【解决方案1】:

你可以试试:

this.refs.messageTextInput.focus();

我是这样使用的 例子:(去掉TextInput的额外代码)

<TextInput
    onSubmitEditing={() => {
        this.refs.PasswordInput.focus();
    }}
/>
<TextInput
    ref='PasswordInput'
/>

【讨论】:

  • 为什么不直接使用 TextInput 的 onFocus 事件呢?
  • onFocus 将是相同的,我添加了示例以将焦点添加到来自另一个输入的一个输入上。如果我们需要在关注输入的同时执行一些操作,那么我们可以使用 onFocus 事件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-04
  • 1970-01-01
  • 2018-06-05
  • 2014-04-24
  • 2010-12-24
  • 2011-03-21
  • 1970-01-01
相关资源
最近更新 更多