TypeError:无法读取ReactJS中未定义的属性'focus'

问题描述 投票:0回答:2
import React, { Component } from "react";
import PropTypes from "prop-types";
import Textarea from "react-textarea-autosize";

class InputSet extends Component {
  constructor(props) {
    super(props);

    this.state = {};
  }


  static propTypes = {
    onChange: PropTypes.func,
    title: PropTypes.string,
    body: PropTypes.string
  };

  componentDidMount() {
    this.title.focus();
  }

  render() {
    const { onChange, title, body } = this.props;

    return (
      <div>
        <TitleInput
          name="title"
          onChange={onChange}
          placeholder="Title"
          innerRef={ref => (this.title = ref)}
          value={title}
        />
        <StyledTextArea
          minRows={3}
          maxRows={20}
          placeholder="Please enter a note..."
          name="body"
          onChange={onChange}
          value={body}
        />
      </div>
    );
  }
}

export default InputSet;

当我单击某个组件时,会突然发生该错误。它说TypeError:无法读取未定义的属性'focus'

错误发生在componentDidMount

您能花点时间帮助我解决此错误吗?

我不明白为什么会出现此错误

javascript reactjs focus
2个回答
0
投票

您必须像这样.current添加this.title.current.focus();

希望这会有所帮助


0
投票

据我所知,title不是InputSet组件的类属性。

我相信您打算利用React.createRef() API将ref附加到您的React元素。

this.title = React.createRef();

在您的构造函数上,

constructor(props){超级(道具);this.state = {};this.title = React.createRef();}

然后,

componentDidMount() {
  if (this.title.current) {
    this.title.current.focus();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.