React Native 中的 ref 是什么,我什么时候应该使用 ref?

what's ref in react native and when should i use ref?

我正在从事 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 以及为什么我们使用输入以及什么时候应该使用 ref ?

如果你想访问 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 将自动获得焦点。