this is my code but I keep getting this error
Uncaught TypeError: Cannot read properties of null (reading 'term')
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.
Also, you need to declare functions not as a variable, but a class instance method and bind them inside the constructor.
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.