TypeError: Cannot read property 'focus' of undefined in ReactJS
TypeError: Cannot read property 'focus' of undefined in ReactJS
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: Cannot read 属性 'focus' of undefined
错误发生在componentDidMount
你能抽时间帮我解决这个错误吗?
我不明白为什么会出现这个错误
你必须像这样添加 .current
this.title.current.focus();
希望对您有所帮助
据我所知,title
不是您的 InputSet
组件的 class 属性。
我相信您打算使用 React.createRef()
API 将 ref
附加到您的 React 元素。
this.title = React.createRef();
在你的构造函数中,
constructor(props) {
super(props);
this.state = {};
this.title = React.createRef();
}
然后,
componentDidMount() {
if (this.title.current) {
this.title.current.focus();
}
}
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: Cannot read 属性 'focus' of undefined
错误发生在componentDidMount
你能抽时间帮我解决这个错误吗?
我不明白为什么会出现这个错误
你必须像这样添加 .current
this.title.current.focus();
希望对您有所帮助
据我所知,title
不是您的 InputSet
组件的 class 属性。
我相信您打算使用 React.createRef()
API 将 ref
附加到您的 React 元素。
this.title = React.createRef();
在你的构造函数中,
constructor(props) {
super(props);
this.state = {};
this.title = React.createRef();
}
然后,
componentDidMount() {
if (this.title.current) {
this.title.current.focus();
}
}