我有以下字段
import React, { Component } from 'react'
import { Field } from 'redux-form'
import RDateRangePicker from '../../../../components/RDateRangePicker/RDateRangePicker'
export default class DateRange extends Component {
constructor (props) {
super(props)
this.state = { dateRangeEmpty: true }
this.handleChange = this.handleChange.bind(this)
}
handleChange (event) {
this.setState({ dateRangeEmpty: true })
}
render () {
let cssClassName = this.state.dateRangeEmpty
? 'form-group has-feedback has-error' : 'form-group has-feedback has-error'
return (
<div className={cssClassName}>
<div className="col-sm-12">Date range:</div>
<div className="col-sm-12">
<Field name="dateRange"
component={RDateRangePicker}
className="form-control"
onChange={this.handleChange}
/>
</div>
</div>
)
}
}
但永远不会触发onChange
。有什么想法吗?
import React, { Component } from 'react'
import DateRangePicker from 'react-bootstrap-daterangepicker'
import moment from 'moment'
import './RDateRangePicker.scss'
export default class RDateRangePicker extends Component {
_formatValue (value) {
return value.startDate.isSame(value.endDate, 'day')
? value.startDate.format('DD/MM/YYYY')
: value.startDate.format('DD/MM/YYYY') + ' - ' + value.endDate.format('DD/MM/YYYY')
}
_handleEvent (event, picker) {
const { input: { onChange } } = this.props
this._input.value = this._formatValue(picker)
onChange({ startDate: picker.startDate, endDate: picker.endDate })
}
render () {
const ranges = {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment()],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
}
return (
<DateRangePicker ranges={ranges} onApply={::this._handleEvent}>
<input
type="text"
className="form-control"
readOnly
style={{ backgroundColor: '#fff' }}
ref={(c) => { this._input = c }}
required
placeholder="Ex. 09/01/2017 - 13/01/2017"
/>
<span className="glyphicon glyphicon-calendar form-control-feedback" aria-hidden="true" />
</DateRangePicker>
)
}
}
答案 0 :(得分:0)
您不能将自定义组件用作redux-form上的字段。您需要创建small wrapper component。在你的情况下,它看起来像这样:
const ReduxFormDateRangePicker = (props) => (
<RDateRangePicker
ranges={props.input.value}
onApply={value => props.input.onChange(value)}
/>
);
此外,您不需要在Field定义的onChange参数:
<Field name="dateRange"
component={RDateRangePicker}
className="form-control"
/>
答案 1 :(得分:-1)
您正在使用不同方式使用字段,请参阅http://redux-form.com/6.4.3/docs/api/Field.md/