尝试为 redux-form 创建一个隐藏字段,然后包装日期选择器,以便它设置隐藏表单字段的值:
// Wrap the Airbnb component so that it conforms to the property API expected by redux-form
// See: https://github.com/erikras/redux-form/issues/1860
// Also, see: https://github.com/airbnb/react-dates/blob/master/examples/SingleDatePickerWrapper.jsx
class DateField extends Component {
// The props are supplied via redux-form's <Field /> component
static propTypes = {
autoFocus: PropTypes.bool.isRequired,
input: PropTypes.shape({
value: PropTypes.string,
onChange: PropTypes.func.isRequired,
onFocus: PropTypes.func.isRequired,
onBlur: PropTypes.func.isRequired
}).isRequired
}
constructor (props) {
super(props)
const { value } = this.props.input
this.state = {
date: (!value || value === '') ? null : moment(value),
focused: this.props.autoFocus
}
}
// Use empty value instead of null to ensure it's treated as a controlled component
getValueAsString = date => (date ? date.toISOString() : '')
handleDateChange = (date, foo) => {
this.setState({ date }, () => {
const dateStr = this.getValueAsString(this.state.date)
this.props.input.onChange(dateStr)
})
}
handleFocusChange = (e) => {
this.setState({ focused: e.focused }, () => {
const date = this.state.date
const dateStr = this.getValueAsString(date)
if (e.focused) {
this.props.input.onFocus(dateStr)
} else {
this.props.input.onBlur(dateStr)
}
})
}
renderHiddenField = field => (
<input {...field.input} type={'hidden'} />
)
render () {
// eslint-disable-next-line
const { name, input, meta, ...rest } = this.props
const dateStr = this.getValueAsString(this.state.date)
return (
<div>
<Field
{...this.props}
name={`_hidden_${input.name}`}
value={dateStr}
component={this.renderHiddenField}
/>
<SingleDatePicker
id={`_wrapped_${input.name}`}
date={this.state.date}
focused={this.state.focused}
onDateChange={this.handleDateChange}
onFocusChange={this.handleFocusChange}
{...rest}
/>
</div>
)
}
}