【发布时间】:2020-12-16 19:51:52
【问题描述】:
我想将这个类组件转换为在函数组件中工作的handleChange 事件。我不完全确定这是可能的,它可能必须是一个钩子。我的语法不太正确。
class CheckboxForm extends Component {
constructor(props) {
super(props);
this.state = { value: [] };
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
const input = event.target.value;
this.setState(
{
value: this.state.value.includes(input)
? this.state.value.filter((item) => item !== input)
: [...this.state.value, input],
},
() => {
console.log("CheckBox: ", this.state.value);
}
);
}
我的尝试:
export const CheckboxHook = (props) => {
const [value, setValue] = useState([]);
const handleCheckbox = (event) => {
const input = event.target.value;
setValue(
value.include(input)
? value.filter((item) => item !== input)
: [value, input],
() => {
console.log("Checkbox: ", value);
}
);
};
};
【问题讨论】:
标签: reactjs react-hooks react-component react-functional-component