[英]Why do I keep getting this error? Uncaught TypeError: Cannot read property 'classList' of null
[英]why do 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;
在 class 組件中使用 state 的正確方法是在構造函數中聲明 state,並使用this.setState
修改 Z9ED36A9E2EA9934258。
此外,您需要將函數聲明為不是變量,而是 class 實例方法並將它們綁定在構造函數中。
代碼將是:
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.