javascript - 尝试使用引用访问同级组件的 TextInput 时“未定义不是对象”
问题描述
在组件中,当在第一个组件中按下提交按钮时Parent
,我试图关注TextInput
第二个组件,但出现此错误:错误消息Child
TextInput
Child
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>
);
}
}
父.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>
);
}
}
推荐阅读
- c++ - 使用 SDL_Rect 指针变量时引发的异常
- flutter - 使用 Flutter Riverpod 的 StreamProvider 从 Firestore 获取特定文档
- linux - 如何使用 shell 脚本从 csv 文件的最后一列进行搜索,结果应包含所有列
- python - 即使脚本工作正常,我的 pygame 图像也不会旋转
- javascript - How to sort fields by date in Javascript?
- python - 如何将此json更改为数据框?
- javascript - 切片方法不删除所有重复项
- javascript - 输入不起作用的React Native清除功能
- python - 从熊猫系列中提取作为字典中值的索引
- java - 由于某种原因找不到我的 Springboot 依赖项