【发布时间】:2018-07-31 21:53:03
【问题描述】:
我创建了一个出生日期组件,它应该有单独的日期、月份和年份字段。该组件将组合这些值并提供 YYYY-MM-DD 格式的日期字符串。
Date of birth 组件的代码
import * as React from 'react';
import * as _ from 'lodash';
import { Col, Input } from 'antd';
const InputGroup = Input.Group;
class DateOfBirthInput extends React.Component<any, any> {
constructor(props: any) {
super(props);
this.state = {
value:{}
};
console.log(props);
}
public handleChange = (event: any) => {
const date:any = _.get(this.state,"value");
if(event.target.id === 'day'){
date.day = event.target.value;
}
if(event.target.id === 'month'){
date.month = event.target.value;
}
if(event.target.id === 'year'){
date.year = event.target.value;
}
this.setState({
value: date
});
}
public render() {
return (
<div>
<div className="ant-form-item-label"><label title="Date of birth">Date of birth</label></div>
<InputGroup>
<Col span={4}>
<Input
placeholder="MM"
id="month"
type="text"
onChange={this.handleChange} />
</Col>
<Col span={1}/>
<Col span={4}>
<Input
placeholder="DD"
id="day"
type="text"
onChange={this.handleChange} />
</Col>
<Col span={1}/>
<Col span={5}>
<Input
placeholder="YYYY"
id="year"
type="text"
onChange={this.handleChange} />
</Col>
<Col>
<h4>Date of birth output: {JSON.stringify(this.state.value)}</h4>
</Col>
</InputGroup>
</div>
);
}
}
export default DateOfBirthInput;
父组件
...
<InputGroup>
<Col span={24}>
<Field
label="Date of Birth"
name="userInfo.dateOfBirth"
placeholder="Date of Birth"
component={DateOfBirthInput}
/>
</Col>
</InputGroup>
...
如何将子组件状态的值传递给父组件?
根据文档,我需要传递 value 和 onChange 事件,它应该可以工作。
https://redux-form.com/6.0.0-alpha.5/docs/faq/customcomponent.md/
我想我在父组件中遗漏了一些东西。 请帮忙。
【问题讨论】:
-
你不能像这样将孩子的状态传递给父组件。通常,您在父级中持有状态。将
handleChange处理程序传递给子代,然后使用此处理程序将相关值传递给父代。父级更新状态。另外,我不知道lodash,但如果_.get没有创建新对象,请不要使用它。状态是可变的,你不应该那样改变它的值。 -
感谢@devserkan 的回答,它帮助我指出了正确的方向。我让组件在 handleChange 函数中处理我的触发输入的 onChange 事件。 const DateString:string = date.year+ '-' + date.month + '-' + date.day; this.props.input.onChange(DateString); }
-
不客气。
标签: javascript reactjs react-redux redux-form