[英]why do i keep getting this error? Uncaught TypeError: Cannot read properties of null (reading 'term')
this is my code but I keep getting this error这是我的代码,但我不断收到此错误
Uncaught TypeError: Cannot read properties of null (reading 'term')
未捕获的类型错误:无法读取 null 的属性(读取“术语”)
import React from "react";
class SearchBar extends React. Component{
State = { term: ''};
onInputChange = event => {
this.setState({ term: event.target.value});
};
onFormSubmit = event => {
event.preventDefault();
this.props.onSubmit(this.state.term)
}
render(){
return(
<div className="Search-bar ui segment ">
<form onSubmit={this.onFormSubmit} className="ui form">
<div className="field">
<label>Video Search</label>
<input className="ui input"
type="text"
value={this.state.term}
onChange={this.onInputChange}
/>
</div>
</form>
</div>
);
}
}
export default SearchBar;
The proper way to use state in class component is to declare state in the constructor, and use this.setState
to modify state.在 class 组件中使用 state 的正确方法是在构造函数中声明 state,并使用
this.setState
修改 Z9ED36A9E2EA9934258。
Also, you need to declare functions not as a variable, but a class instance method and bind them inside the constructor.此外,您需要将函数声明为不是变量,而是 class 实例方法并将它们绑定在构造函数中。
The code would be:代码将是:
import React from 'react';
class SearchBar extends React.component {
constructor(props) {
super(props);
this.state = {
term: ''
};
this.onInputChange = this.onInputChange.bind(this);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onInputChange(event) {
this.setState({ term: event.target.value });
}
onFormSubmit(event) {
event.preventDefault();
this.props.onSubmit(this.state.term);
}
render() {
return (
<div className="Search-bar ui segment ">
<form onSubmit={this.onFormSubmit} className="ui form">
<div className="field">
<label>Video Search</label>
<input className="ui input"
type="text"
value={this.state.term}
onChange={this.onInputChange}
/>
</div>
</form>
</div>
);
}
}
export default SearchBar;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.