简体   繁体   中英

Pass component state to redux-form

I am using react-day-picker with multi day select http://react-day-picker.js.org/examples/selected-multiple .

My question: Is it possible to pass state of this component:

export default class MultiDayPicker extends Component {
state = {
   selectedDays: []
};

handleDayClick = (day, {selected}) => {
   const {selectedDays} = this.state;

if (selected) {
  const selectedIndex = selectedDays.findIndex(selectedDay =>
    DateUtils.isSameDay(selectedDay, day)
  );

  selectedDays.splice(selectedIndex, 1);
} else {
  selectedDays.push(day);
}
this.setState({selectedDays});
 };

 render() {
return (
  <div>
    <DayPicker
      selectedDays={this.state.selectedDays}
      onDayClick={this.handleDayClick}
    />
  </div>
);

to redux-form state ??

<Field
    name="dates"
    component={MutliDayPicker}
/>

In your custom MultiDayPicker component you have to call redux-form input.onChange method.

So in order to change the redux-form state, when your MultiDayPicker value is changed, you have to add the following redux-form api call in handleDayClick :

handleDayClick( day, { selected }) => {
  // Rest code here ...

  // Update `redux-form` state
  this.props.input.onChange(selectedDays)
}

Also you have to think about the rest redux-form input properties and callbacks and decide for which ones to add support. Here's the full list .

I've never used the DayPicker, but i've used DayPickerInput, if you can it instead of DayPicker, you can simply put inside DayPickerInput inputProps={{...this.props.input}} as inputProps is defined as additional props to add to the input component.

Redux Form need to find the input name inside of the field you pass from Field to bind the value.

You should also use onDayChange instead of onDayClick i guess.

Code:

<DayPickerInput inputProps={{...this.props.input}} onDayChange={this.props.input.onChange} />

You can find more information here: DayPickerInput: inputProps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM