[英]React - prop is undefined when loading the same component
我正面臨一個React組件的問題,我希望在一個案例中使用某個道具而在另一個案例中使用另一個道具。 讓我告訴你我的意思。
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}/>
行添加到代碼中時。
為什么它是未定義的,因為我正在定義它在道具中的含義?
首先,確保SomeBoolean
和field1.subfield
/ field2.subfield
屬性正確傳遞。
我的推薦是:在將參數傳遞給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} />
結果將與您寫的相同:
<WidgetColumn field1={this.props.field1} field2={this.props.field2} />
您可能存在沖突,並且傳播對象會重寫您手動定義的道具的值。 嘗試在下一個方向傳遞字段屬性:
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>
渲染組件時必須聲明屬性。 喜歡
<WidgetColumn props={this.props} field1={this.props.field2}/>
如果使用此方法,則可以訪問子組件中父組件的所有道具 。
而已。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.