我正在尝试将属性传递给子组件,但是当我尝试从子组件中访问它们时,它们是undefined
。
我正在创建一些表单,我的想法是创建一个由所有表单使用的父组件LoginPanel
,在本例中为ResetForm
这是我的父组件
var LoginPanel = React.createClass({
getInitialState: function() {
return {status: false};
},
render() {
// add props to children
const childrenWithProps = React.Children.map(this.props.children,
(child) => React.cloneElement(child, {
status: this.state.status
})
);
console.log(childrenWithProps[0]);
// the new props (status) are copied, but previous properties (resetUrl) don't exist
// this is the shortened html
return (
<div className="container">
{childrenWithProps}
</div>
);
}
})
这是我的孩子组件
var ResetForm = React.createClass({
componentDidMount() {
console.log("done:", this.props.status); // this.props.status is undefined
},
render()
console.log("status:", this.props.status); // this.props.status is undefined
// shortened html
return (
<LoginPanel>
<p>...</p>
</LoginPanel>
);
}
});
ReactDOM.render(
<ResetForm resetUrl={resetUrl}/>,
document.getElementById('content')
);
这是我的控制台输出
status: undefined
child: Object {...}
done: undefined
我也从控制台中的React收到错误消息(我实际上是尝试传递更多属性,只是将我的示例限制为status
属性)但我不明白是什么问题。属性未知。那我怎么能让React了解道具呢?
"Warning: Unknown props `statuses`, `status`, `message`, `updateStatus` on <form> tag. Remove these props from the element. For details, see fb.me/react-unknown-prop
in form (created by ResetForm)
in div (created by LoginPanel)
in div (created by LoginPanel)
in div (created by LoginPanel)
in LoginPanel (created by ResetForm)
in ResetForm"
我已经找到了解释如何将道具传递给子组件的其他SO答案,我试图做同样的事情。但显然我做错了什么,我找不到问题。有什么想法吗?
答案 0 :(得分:0)
我建议您在LoginPanel
中进行两次更正,而您似乎忘记定义state status
。包括它:
getInitialState: function() {
return {status: false};
},
还在您的子组件中包含getDefaultProps()
getDefaultProps: function() {
return {state: null};
}
答案 1 :(得分:0)
好的,事实证明,在渲染子组件时,父组件必须放在ReactDOM.render()
函数中,而不是放在组件本身的render()
函数中。这就是我修复子组件的方法:
var ResetForm = React.createClass({
componentDidMount() {
console.log("done:", this.props.status);
},
render()
console.log("status:", this.props.status);
// move <LoginPanel> from here ...
return (
<p>...</p>
);
}
});
ReactDOM.render(
// ... to here
<LoginPanel>
<ResetForm resetUrl={resetUrl}/>
</LoginPanel>,
document.getElementById('content')
);