首页 > 解决方案 > 尝试使用引用访问同级组件的 TextInput 时“未定义不是对象”

问题描述

在组件中,当在第一个组件中按下提交按钮时Parent,我试图关注TextInput第二个组件,但出现此错误:错误消息ChildTextInputChild

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在安装后三秒成功聚焦。

标签: javascriptreactjsreact-native

解决方案


我认为渲染更新中的问题。在第一次渲染时间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>
    );
  }
}

推荐阅读