Javascript React-加载同一组件时,prop未定义
我面临着一个React组件的问题,我想在一种情况下使用某个道具,在另一种情况下使用另一个道具。让我告诉你我的意思Javascript React-加载同一组件时,prop未定义,javascript,reactjs,Javascript,Reactjs,我面临着一个React组件的问题,我想在一种情况下使用某个道具,在另一种情况下使用另一个道具。让我告诉你我的意思 class GizmoComponent extends React.Component { render() { return ( { this.props.SomeBoolean ? <WidgetColumn {...this.p
class GizmoComponent extends React.Component {
render() {
return (
{
this.props.SomeBoolean
?
<WidgetColumn {...this.props} field1={this.props.field2}/>
:
<WidgetColumn {...this.props} field1={this.props.field1}/> {/* field1 is already in the props but I'm being explicit */}
}
);
}
}
class WidgetColumn extends React.Component {
render() {
return (
{
this.props.field1.subfield
?
<div>{/* Extensive use of this.props.field1 throughout this component*/}</div>
:
<div></div>
}
);
}
}
类GizmoComponent扩展了React.Component{
render(){
返回(
{
这是我的道具
?
:
{/*field1已经在道具中,但我是显式的*/}
}
);
}
}
类WidgetColumn扩展了React.Component{
render(){
返回(
{
this.props.field1.subfield
?
{/*在整个组件中广泛使用this.props.field1*/}
:
}
);
}
}
基本上,我想做的是,因为WidgetColumn
广泛使用了this.props.field1
,所以我想用field2
代替获取该数据。其他一切都是一样的。在特定情况下,只需从不同的项获取数据:SomeBoolean
但是,我在this.props.field1.子字段
上得到一个错误,说this.props.field1
未定义,因此我无法获取未定义的内容的子字段
。仅当我将
行添加到代码中时,才会发生这种情况
既然我正在定义道具中的内容,为什么它没有定义?首先,请确保
SomeBoolean
和field1.子字段
/field2.子字段
属性正确传递
我的建议是:在向WidgetColumn传递参数时,尽量不要{…this.props}
据我所知,GizmoComponent
具有field1
和field2
道具:
GizmoComponent.propTypes = {
field1: PropTypes.object
field2: PropTypes.object
}
因此,当您将GizmoComponent
道具扩展到另一个组件时,如:
// NOTE: there are this.props.field1 and this.props.field2 are available
<WidgetColumn {...this.props} />
//注意:有this.props.field1和this.props.field2可用
结果将与您所写的相同:
<WidgetColumn field1={this.props.field1} field2={this.props.field2} />
可能存在冲突,并且spread object会重写手动定义的道具值。
尝试下一步传递字段属性:
类WidgetColumn扩展了React.Component{
render(){
返回此.props.field.subfield
?该字段为子字段
:该字段不是子字段
}
}
类GizmoComponent扩展了React.Component{
render(){
返回this.props.SomeBoolean
?
:
}
}
类示例扩展了React.Component{
render(){
返回(
);
}
}
ReactDOM.render(
,
document.getElementById('root'))
);代码>
呈现组件时必须声明属性。
像
如果使用此选项,则可以访问子组件中父组件的所有道具
就是这样。您确定Gizmo组件中this.props.field1和this.props.field2的值没有未定义吗?在我看来,所有内容都正确地传递给了WidgetColumn,这只是它们的值对这一点很重要。如果不有条件地呈现WidgetColumn,您可以有条件地将道具设置为组件。只是一个进步。如果你能记录道具对象,并将其发布在这里,以获得“someBoolean”的true和false状态,这将完全有助于解决你的问题
<WidgetColumn props={this.props} field1={this.props.field2}/>