【问题标题】:what's ref in react native and when should i use ref?react native 中的 ref 是什么,我什么时候应该使用 ref?
【发布时间】:2020-02-11 03:18:21
【问题描述】:

我正在开发 React Native 项目,我使用 React Native 组件创建了表单。 我使用 TextInput 来编辑这样的状态值:

<TextInput
    shake
    keyboardAppearance='light'
    autoFocus={false}
    autoCapitalize='none'
    autoCorrect={false}
    keyboardType='default'
    returnKeyType='next'
    value={this.state.sector}
    onChangeText={sector => this.setState({ sector })}
/>

使用 console.log 扇区值,我在输入更改后正确地获得了当前值,但我已经看到了一些这样的 ref 示例:

<TextInput
    shake
    keyboardAppearance='light'
    autoFocus={false}
    autoCapitalize='none'
    autoCorrect={false}
    keyboardType='default'
    returnKeyType='next'
    value={this.state.sector}
    ref={input => (this.sectorInput = input)}
    onChangeText={sector => this.setState({ sector })}
/>

我不明白这个操作:

ref={input => (this.sectorInput = input)}

有人可以解释什么是 ref 以及我们为什么使用 input 以及何时应该使用 ref ?

【问题讨论】:

    标签: forms react-native ref


    【解决方案1】:

    如果你想访问 TextInput methods 那么你必须创建该组件的引用,然后使用引用你可以使用它的方法。

    例如,您的应用程序中有表单,并且您希望在用户填写第一个字段之后,您希望将焦点设置在下一个字段上,然后您可以这样做:

    <TextInput
        shake
        keyboardAppearance='light'
        autoFocus={false}
        autoCapitalize='none'
        autoCorrect={false}
        keyboardType='default'
        returnKeyType='next'
        value={this.state.sector}
        ref={input => { this.sectorInput = input}}
        onSubmitEditing={() => {
            this.nextField.focus();
        }}
        onChangeText={sector => this.setState({ sector })}
    />
    
    <TextInput
        shake
        keyboardAppearance='light'
        autoFocus={false}
        autoCapitalize='none'
        autoCorrect={false}
        keyboardType='default'
        returnKeyType='next'
        value={this.state.sector}
        ref={input => { this.nextField = input}}
        onSubmitEditing={() => {
            this.handleSubmit();
        }}
        onChangeText={nextField => this.setState({ nextField })}
    />
    

    现在,当用户填写sector 字段时,如果他按下一步,那么nextField 将自动获得焦点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      相关资源
      最近更新 更多