我无法将日期值从react-dates组件传递到它的父组件。
首先,我通常会使用Redux来处理这样的任务,但这对项目来说太过分了,我更喜欢简单的解决方案。
如何将onChange
事件从DateRangePicker
它的父组件传递?
父组件
...
import DateRangePicker from './DatepickerRates'
class Rates extends Component {
constructor(props) {
super(props);
this.state = { }
}
onChange(startDate, endDate) {
this.setState({[startDate]: startDate});
this.setState({[endDate]: endDate});
}
render() {
console.log(`In ${this.state.startDate} - Out ${this.state.endDate}`)
return (
<Wrapper>
<DateRangePicker onChange={this.onChange.bind(this)}/>
</Wrapper>
);
}
}
export default Rates;
日期范围选择器
...
class DateRangePickerWrapper extends Component {
constructor(props) {
super(props);
this.state = {
focusedInput,
startDate: props.initialStartDate,
endDate: props.initialEndDate,
}
this.onDatesChange = this.onDatesChange.bind(this);
this.onFocusChange = this.onFocusChange.bind(this);
}
onDatesChange({ startDate, endDate }) {
const { stateDateWrapper } = this.props;
this.props.onChange('startDate', this.state.startDate);
this.props.onChange('endDate', this.state.endDate);
this.setState({
startDate: startDate && stateDateWrapper(startDate),
endDate: endDate && stateDateWrapper(endDate),
});
}
render() {
const { startDate, endDate } = this.state;
...
return (
<div>
<DateRangePicker
{...props}
onDatesChange={this.onDatesChange}
onFocusChange={this.onFocusChange}
focusedInput={focusedInput}
startDate={startDate}
endDate={endDate}
/>
</div>
);
}
}
export default DateRangePickerWrapper;