我正面临一个 React 组件的问题,我想在一种情况下使用某个 Prop ,在另一种情况下使用另一个 Prop 。让我告诉你我的意思。
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>
}
);
}
}
基本上,我想做的是因为 WidgetColumn
广泛使用this.props.field1
,我想用 field2
代替获取该数据.其他一切都保持不变。在特定情况下,只需从不同的项目中获取数据:SomeBoolean
.
但是,我在 this.props.field1.subfield
上收到错误消息说this.props.field1
未定义,所以我无法获得 subfield
一些未定义的东西。这仅在我添加 <WidgetColumn {...this.props} field1={this.props.field2}/>
时发生代码行。
为什么它是未定义的,因为我在 prop 中定义它是什么?
最佳答案
首先,确保 SomeBoolean
和 field1.subfield
/field2.subfield
属性正确传递。
我的建议是:尽量不要 spread props object {...this.props}
将参数传递给 WidgetColumn 时。
据我所知,GizmoComponent
有 field1
和 field2
Prop :
GizmoComponent.propTypes = {
field1: PropTypes.object
field2: PropTypes.object
}
因此,当您将 GizmoComponent
Prop 传播到另一个组件时,例如:
// NOTE: there are this.props.field1 and this.props.field2 are available
<WidgetColumn {...this.props} />
结果和你写的一样:
<WidgetColumn field1={this.props.field1} field2={this.props.field2} />
您可能有冲突并且传播对象重写了您手动定义的 Prop 的值。 尝试通过下一种方式传递字段属性:
class WidgetColumn extends React.Component {
render() {
return this.props.field.subfield
? <div>The field is subfield</div>
: <div>The field is NOT subfield</div>
}
}
class GizmoComponent extends React.Component {
render() {
return this.props.SomeBoolean
? <WidgetColumn field={this.props.field2} />
: <WidgetColumn field={this.props.field1} />
}
}
class Example extends React.Component {
render() {
return (
<p>
<GizmoComponent field1={{ subfield: true }} field2={{ subfield: false }} SomeBoolean={true} />
<GizmoComponent field1={{ subfield: true }} field2={{ subfield: false }} SomeBoolean={false} />
</p>
);
}
}
ReactDOM.render(
<Example />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
关于javascript - React - 加载相同组件时属性未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48179599/