如何从子组件更改父状态(startDate)? (使用反应 DatePicker)

How to change parent state(startDate) from child component? (using react DatePicker)

Audiences.js 是父组件,Condition.js 是子组件。 我想更改 startDate(父组件),但 Condition.js 中的“onDateChange”不起作用。

这是我的代码:

class 受众扩展组件 {

state = {
    type: '',
    startDate: new Date()
}

handleDateChange = (date)=> {
    console.log(date)
    alert(date);
    this.setState({
        startDate: date
    });
}

render() {
    const { type, startDate } = this.state;
    const {
        handleDateChange
    } = this;

    return (
    
        <Condition type={type} date={startDate} onChange={handleDateChange} />
    );
}

}

const Condition = ({ type, date, onDateChange }) => {
    return (
        <div className="condition">
            App Usage Settings and Scope
            <hr />
            <DatePicker
                selected={date}
                onChange={onDateChange}
            />

        </div>
    );

};

看起来您的函数命名有误...onChange={handleDateChange} 应该是 onDateChange={handleDateChange}。或者相反,您可以完成 const Condition = ({ type, date, onChange}).

免责声明:会发表评论,但我没有足够的积分。但对我来说这似乎是个问题。