首页 > 解决方案 > 无法在 react-native 中创建 ref

问题描述

我想将重点放在下一次TextInput使用createRef(). 我在createRef(). 我究竟做错了什么?提前致谢。

constructor(props) {
        super(props);
            this.r2Ref = React.createRef();
            this.r3Ref = React.createRef();
            this.r4Ref = React.createRef();
            this.r5Ref = React.createRef();
    }

render() {
        return (
            <View style={SetStyle.settingsCont}>
            <ScrollView>

                <View style={SetStyle.contRate}>

                    <View style={SetStyle.rView}>
                        <Text style={SetStyle.rText}>Rate1</Text>
                        <TextInput style={SetStyle.rInput} keyboardType='numeric'
                            returnKeyType="next" onSubmitEditing={() => this.refs.r2Ref.focus()}></TextInput>
                    </View>
                    <View style={SetStyle.rView}>
                        <Text style={SetStyle.rText}>Rate2</Text>
                        <TextInput style={SetStyle.rInput} keyboardType='numeric'
                            ref={r2Ref => this.r2Ref = r2Ref}
                            returnKeyType="next" onSubimitEditing={() => this.refs.r3Ref.focus()}></TextInput>
                    </View>
                    <View style={SetStyle.rView}>
                        <Text style={SetStyle.rText}>Rate3</Text>
                        <TextInput style={SetStyle.rInput} keyboardType='numeric'
                        ref={r3Ref => this.r3Ref = r3Ref}
                        returnKeyType="next" onSubmitEditing={() => this.refs.r4Ref.focus()}></TextInput>
                    </View>
                    <View style={SetStyle.rView}>
                        <Text style={SetStyle.rText}>Rate4</Text>
                        <TextInput style={SetStyle.rInput} keyboardType='numeric'
                            ref={r4Ref => this.r4Ref = r4Ref}
                            returnKeyType="next" onSubmitEditing={() => this.refs.r5Ref.focus()}></TextInput>
                    </View>
                    <View style={SetStyle.rView}>
                        <Text style={SetStyle.rText}>Rate5</Text>
                        <TextInput style={SetStyle.rInput} keyboardType='numeric'
                            ref={r5Ref => this.r5Ref = r5Ref}></TextInput>
                    </View>
                </View>

            </ScrollView>
            </View>
        );
    }
}

我收到以下错误:

未定义不是对象(评估 this2.refs.r2Refs.focus)

标签: reactjsreact-nativetextinput

解决方案


这里的问题是您将Callback RefscreateRef API 混合在一起。您也错误地访问它们。将它们定义为变量后,您需要改用所述变量。

您需要做的是:

class Component extends React.Component {
  r2Ref = React.createRef();

  render() {
    return <Input name="r2" ref={this.r2Ref} />
  }
}

推荐阅读