我需要将基于类的组件转换为基于函数的组件。转换此代码后,我收到编译错误,因为“filterText”被分配了一个值但从未使用过 no-unused-vars “inStockOnly”被分配了一个值但从未使用过 no -未使用的变量
无法确定我哪里出错了。
基于类的代码是
import React, { Component } from 'react';
class SearchBar extends Component {
constructor(props) {
super(props);
this.handleFilterTextChange = this.handleFilterTextChange.bind(this);
this.handleInStockChange = this.handleInStockChange.bind(this);
}
handleFilterTextChange(e) {
this.props.onFilterTextChange(e.target.value);
}
handleInStockChange(e) {
this.props.onInStockChange(e.target.checked);
}
render() {
return (
<form>
<input
type="text"
placeholder="Search..."
value={this.props.filterText}
onChange={this.handleFilterTextChange}
/>
<p>
<input
type="checkbox"
checked={this.props.inStockOnly}
onChange={this.handleInStockChange}
/>
{' '}
Only show products in stock
</p>
</form>
);
}
}
export default SearchBar;
更改为基于以下功能:
import React, { useState } from 'react';
function SearchBar(props){
const [filterText,setOnFilterTextChange] = useState('');
const [inStockOnly,setOnInStockChange] = useState(false);
const handleFilterTextChange=(e)=> {
setOnFilterTextChange(e.target.value);
}
const handleInStockChange=(e)=> {
setOnInStockChange(e.target.checked);
}
return (
<form>
<input
type="text"
placeholder="Search..."
value={props.filterText}
onChange={handleFilterTextChange}
/>
<p>
<input
type="checkbox"
checked={props.inStockOnly}
onChange={handleInStockChange}
/>
{' '}
Only show products in stock
</p>
</form>
);
}
export default SearchBar;
四季花海
噜噜哒
相关分类