gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'focus' of undefined in ReactJS

转载 作者:行者123 更新时间:2023-12-03 07:25:22 26 4
gpt4 key购买 nike

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;

当我单击某个组件时,突然出现该错误。它说类型错误:无法读取未定义的属性“焦点”

错误发生在componentDidMount

您能花点时间帮我解决这个错误吗?

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

最佳答案

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

我相信您打算使用 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();
}
}

关于javascript - 类型错误 : Cannot read property 'focus' of undefined in ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59479589/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com