尝试使用引用访问同级组件的文本输入时"undefined is not an object"



Parent组件中,当按下第一个Child组件的TextInput中的提交按钮时,我正试图聚焦第二个Child组件的TextInput,但出现了此错误:错误消息

Child.js

import React from "react";
import { View, TextInput} from "react-native";
export default class Child extends React.Component {
focus = ref => {
ref.input.focus();
};
render() {
return (
<View>
<TextInput
placeholder='enter text'
onSubmitEditing={() => {
this.focus(this.props.destinationRef);
}}
ref={input => {
this.input = input;
}}
/>
</View>
);
}
}

Parent.js

import React from "react";
import Child from "./Child";
import { View, StyleSheet } from "react-native";
export default class Parent extends React.Component {
//   componentDidMount() {
//     setTimeout(() => {
//       this.two.input.focus();
//     }, 3000);
//   }
render() {
return (
<View style={styles.container}>
<Child
destinationRef={() => {
if (!this.two) return this.two;
}}
ref={input => {
this.one = input;
}}
/>
<Child ref={input => (this.two = input)} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center"
}
});

请注意,当我取消对componendDidMount的注释时,第二个TextInput在安装后三秒成功聚焦。

我认为渲染更新中存在问题。在第一次渲染时,destinationRef未定义,父状态未更新或强制更新,因此道具也未更新。

我试着稍微优化一下你的代码。您可以使用箭头函数绑定this:

import React from "react";
import Child from "./Child";
import { View, StyleSheet } from "react-native";
export default class Parent extends React.Component {
_makeFocus(){
this.two.input.focus();
}
handleOnSubmit(){
this._makeFocus();
}
render() {
return (
<View style={styles.container}>
<Child
onSubmit={this.handleOnSubmit.bind(this)}
ref={input => {
this.one = input;
}}
/>
<Child ref={input => (this.two = input)} />
</View>
);
}
}

我会稍微改变一下逻辑,因为我认为ref给你带来了问题。

父级:

<View style={styles.container}>
<Child next={this.two} ref={comp => this.one = comp}/>
<Child next={this.one} ref={comp => this.two = comp}/>
</View>

儿童:

<TextInput
placeholder='enter text'
onSubmitEditing={() => {
if (this.props.next)
this.props.next.focus();
}}
/>

编辑:

我相信你的方法是正确的,我只想把家长更新成这样:

export default class Parent extends React.Component {
constructor(props){
super(props);
this.references = {};
}
onFocus = (ref) => {
this.references[ref].focus();
}
render() {
return (
<View style={styles.container}>
<Child
destinationRef={'two'}
onFocus={this.onFocus}
ref={input => this.references['one'] = input}
/>
<Child ref={input => this.references['two'] = input} />
</View>
);
}
}

和您的孩子:

export default class Child extends React.Component {
render() {
return (
<View>
<TextInput
placeholder='enter text'
onSubmitEditing={() => {
this.props.onFocus(this.props.destinationRef);
}}
/>
</View>
);
}
}

相关内容

  • 没有找到相关文章

最新更新