我正在尝试使用挂钩将遗留代码库从基于类迁移到基于函数。
旧代码就像:
constructor(props){
super(props)
this.state = {
pickerProps: {
onPickDate: this.onPickDate,
activeColor: "#119955",
date: "12-12-2012"
},
inputStyle: "",
selectedDate: null
}
}
onPickDate = date => {
this.setState((state) => ({
selectedDate: date
}))
}
onInputChange = (prop, value) => {
this.setState((state) => ({
pickerProps: {
...state.pickerProps,
[prop]: value
}
}))
}
changeInputStyle = e => {
const value = e.target.value
this.setState((state) => ({inputStyle: value}))
}
,新代码为:
const [inputStyle, setInputStyle] = useState("");
const [selectedDate, setSelectedDate] = useState(null);
const [pickerProps, setPickerProps] = useState({
onPickDate:onPickDate, // How to pass function here
activeColor: "#119955",
date: "12-12-2012",
});
// This is the function I want to pass to useState()
const onPickDate = (date) => {
setSelectedDate(date);
};
const onInputChange = (prop, value) => {
setPickerProps({ [prop]: value });
};
const changeInputStyle = (e) => {
const value = e.target.value;
setInputStyle(value);
};
我收到警告:The onPickDate was used before defined
当我将pickerProps
发送到DatePicker
时:
<div className="date-picker">
<DatePicker {...pickerProps} />
</div>
它会引发错误:
OnPickDate is not defined ()