【问题标题】:React.createRef() on TextInput no working in React Native 16.3.1TextInput 上的 React.createRef() 在 React Native 16.3.1 中不起作用
【发布时间】:2018-08-24 02:41:23
【问题描述】:

我有一个 Textinput,我想在光标未填充时设置它。

class SignupScreen extends Component {
  constructor(props) {
    super(props);
    this.fieldOne = React.createRef(); 
    this.state = {
        name: '',
    }
}

validate() {
   if(_.size(this.state.name) < 3) {
      ...
      this.fieldOne.current.focus() // this is not working
    }
}

render() {
return(
.... 
<TextInput
    placeholder={'Name'}
    autoCapitalize='words'
    autoCorrect={false}
    autoFocus={false}
    keyboardType='default'
    value={this.state.name}
    ref={this.fieldOne}
    selectionColor={colors.PRIMARY_LIGHT}
    placeholderTextColor={colors.PRIMARY_LIGHT}
    underlineColorAndroid={colors.NO_COLOR}
    onChangeText={(text) => this.setState({ name: text })}
/>
 ...
}

在验证方法中,当光标不正确时,我想将光标聚焦在字段中。我在互联网上查看过,我也将这个问题作为问题发布在https://github.com/facebook/react-native/issues/20817。虽然,我还没有找到真正的解决方案。

谢谢你!

【问题讨论】:

    标签: javascript react-native expo


    【解决方案1】:

    你需要bind你的validate函数,或者使用箭头函数。

    您可以在constructor 的底部添加以下内容

    this.validate = this.validate.bind(this);
    

    或者,将您的函数更改为箭头函数

    validate = () => {
      // Function body
    }
    

    这里是example,点击按钮会聚焦TextInput

    【讨论】:

      【解决方案2】:

      谢谢@丹!感谢您的回答,尤其是示例!但是,它对我没有用。无论如何,我已经安装了 react-native-elements 并且一直在使用这些东西。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-13
        • 2018-07-12
        • 2021-05-17
        • 1970-01-01
        • 2021-10-12
        • 2023-02-25
        相关资源
        最近更新 更多