【发布时间】:2017-04-26 09:39:21
【问题描述】:
所以,我的组件从父组件接收一个对象,该对象如下所示:
{
_id: Data.now(), // MongoDB database
name: "",
description: "",
image: "images/image.jpg",
type: "image"
}
在我的子组件中,我想获取这些数据并为每个数据进行输入,这样我就可以更改值,然后保存新数据。
更新答案(es6 类):
constructor(props) {
super();
this.state = {
fieldGroups: []
}
this.parseProps = this.parseProps.bind(this);
}
componentWillMount() {
this.parseProps(this.props);
}
componentWillReceiveProps(nextProps) {
this.parseProps(nextProps);
}
parseProps(props) {
var fieldsArray = [];
var content = props.content;
Object.keys(content).map((field,index) => {
if (field === 'type') {
let fieldObj = {};
fieldObj.field = field;
fieldObj.value = content[field];
fieldObj.key = props.content._id + field;
fieldsArray.push(fieldObj);
}
});
this.setState({
fieldGroups: fieldsArray
});
}
render() {
return (
{
this.state.fieldGroups.map((field) => {
if (field.field === "type") {
return ( html element specific to type )
} else {
return ( a different html element )
}
})
}
)
}
所以现在我可以在让子组件决定向用户显示哪些字段的意义上分离我的组件。谢谢 DanneManne
【问题讨论】:
-
很难从这个不完整的例子中看出。你能展示更多关于这个组件的代码吗?是一堂课吗?您是否正确实现了构造函数? stackoverflow.com/help/mcve
标签: reactjs meteor ecmascript-6