尝试让Calendar使用Redux Form
使用Redux表单字段:
SuppressWarnings
利用无状态功能:
<Field name={name} component={this.renderCal}/>
当我提交表单时,该值仍为null。我看起来像值没有绑定到组件。这是我在Chrome开发者工具中的请求负载&gt;网络......
renderCal({input, ...rest}) {
input.value = new Date();
return <Calendar {...input}
onChange={() => input.onChange(input.value)}
value={input.value}
{...rest}/>
}
是否有人将日历与Redux Form一起用作无状态函数?
谢谢, 史蒂夫
答案 0 :(得分:0)
为了澄清,表单的初始状态/形状实际上是一个日期数组:
{
myDates: [
{myDate: null},
{myDate: null},
{myDate: null}
]
}
如果您只需将DateTimePicker绑定到Redux表单字段,则可以直接删除 renderDynamicField s 并使用 renderDynamicField :
<Field name={name} component={renderDynamicField}/>
注意事项:
<强>解决方案强>
import React from "react";
import {Button, Col, Form, FormGroup, ControlLabel} from "react-bootstrap";
import {reduxForm, Field, FieldArray} from "redux-form";
import {connect} from "react-redux";
import {DateTimePicker} from "react-widgets";
class ReactWidgets extends React.Component {
constructor(props) {
super(props);
this.renderDynamicFields = this.renderDynamicFields.bind(this);
}
submit(form) {
console.log('form', form);
}
renderDynamicFields({fields = []}) {
let collection = [];
fields.map((name, index) => {
collection.push(<Field key={index} name={`${name}.myDate`} component={renderDynamicField}/>);
});
return <div>{collection}</div>;
function renderDynamicField(props) {
const {input} = props;
let component = null;
if (true) { // going to support different types...
component = <DateTimePicker
defaultValue={input.value || new Date()}
onChange={(value) => {
input.onChange(value);
}}/>;
}
return component;
}
}
render() {
const {error, handleSubmit, pristine, reset, submitting} = this.props;
return (
<Form horizontal onSubmit={handleSubmit(this.submit)}>
<FormGroup><Col componentClass={ControlLabel} xs={2}>
My Date2</Col>
<Col xs={4}>
<FieldArray name="myDates" component={this.renderDynamicFields}/>
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={1} xs={11}>
<Button type="submit" bsStyle="primary"
disabled={pristine || submitting}>Save</Button>
<Button type="button" disabled={pristine || submitting}
onClick={reset}>Reset</Button>
</Col>
</FormGroup>
</Form>
);
}
}
ReactWidgets = reduxForm({
form: 'reactWidgets'
})(ReactWidgets);
ReactWidgets = connect(
state => {
return {
initialValues: {
myDates: [
{myDate: null},
{myDate: null},
{myDate: null}
]
},
}
})(ReactWidgets)
export default ReactWidgets