什么是ref本机,我应该何时使用ref?

问题描述 投票:0回答:1

我正在研究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?

forms react-native ref
1个回答
0
投票

如果要访问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将自动聚焦。

© www.soinside.com 2019 - 2024. All rights reserved.