簡體   English   中英

使用帶有redux-form的react-datepicker

[英]Using react-datepicker with redux-form

我正在嘗試使用帶有redux-form的react-datepicker,我正面臨一個問題。 當我從日期選擇器中選擇日期時,我收到以下錯誤:

Uncaught TypeError: t.isSame is not a function

我的代碼如下:

// My component that uses the date picker
const renderDateField = (field) => {
  return (
    <div>
      <img src={require('./images/date.png')} className={styles.iconField} />
      <DatePicker {...field.input} placeholderText={field.placeholder} onChange={field.onDateChange} dateFormat='DD/MM/YYYY' selected={field.selected ? field.selected : null} className={styles.inputField} />
    </div>
  );
};

export class MyComponent extends React.Component {

  constructor (props) {
    super(props);
    this.state = {
      startDate: moment()
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange (date) {
    console.log('handle Change', date);
    this.setState({
      startDate: date.format('DD/MM/YYYY')
    });
  }

  render () {
    const { handleSubmit } = this.props;
    console.log('Render global state.startDate', this.state.startDate);
    return (
      <div>
        <form onSubmit={handleSubmit(this.props.filterSubmit)} method='post' action='/tennis/search'>
                ...
                <Field name='date' placeholder='Quand ?' component={renderDateField} onDateChange={this.handleChange} selected={this.state.startDate} />
                ...
        </form>
      </div>)
    ;
  }
}
...
TennisSearchFilters.propTypes = {
  filters: React.PropTypes.shape({
    date: React.PropTypes.object
  }),
  filterSubmit: React.PropTypes.func.isRequired,
  handleSubmit: propTypes.handleSubmit
};
    ...
export default reduxForm({
          form: 'tennisSearch',
          validate: validateTennisSearchForm
        })(TennisSearchFilters);

我認為存在格式錯誤,因為輸入值似乎更新為字符串,然后在將時刻與字符串進行比較時崩潰。 但我不太確定...所以我請求你的幫助:)

我檢查了其他人關於它的帖子和問題,但它沒有正常工作(也許我做錯了但是)。

非常感謝你的幫助!

看看提供的代碼示例,我假設react-datepicker正在使用moment

onChange方法接收moment實例,您將此實例轉換為純字符串。 然后, react-datepicker isSame嘗試在字符串值上調用isSame方法,這當然會失敗。

而不是將更新的值轉換為字符串,而是按原樣存儲。

this.setState({
    startDate: date,
});

試試你的日歷組件::

 onChange ={val => {
   field.onDateChange // Rather read the value from redux-form
   return field.input.onChange(val) // This should dispatch the value to redux-form
  }
}

在使用redux-form時,不確定為什么要在此處設置其他視圖狀態?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM