如何在useState()中将函数作为对象的初始值传递?

时间:2020-05-08 07:42:04

标签: reactjs react-hooks

我正在尝试使用挂钩将遗留代码库从基于类迁移到基于函数。

旧代码就像:

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 ()

0 个答案:

没有答案