簡體   English   中英

React:將道具添加到現有組件

[英]React: adding props to an existing component

我試圖弄清楚如何使用其他道具克隆現有元素。

以供參考:

this.mainContent = <Hello message="Hello world!" />

我試圖做類似的事情

React.createElement(this.mainContent, Object.assign({}, 
   this.mainContent.props, { anotherMessage: "nice to meet ya!" }));

但它不起作用。

我怎么做到這一點?

您需要使用React.cloneElement克隆元素並添加其他道具,例如:

var clonedElementWithMoreProps = React.cloneElement(
    this.mainContent, 
    { anotherMessage: "nice to meet ya!" }
);
// now render the new cloned element?

如果您不想使用React.cloneElement() ,則可以使用以下代碼段:

function AddExtraProps(Component, extraProps) {
    return <Component.type {...Component.props} {...extraProps} />;
}

React.createElement()將字符串或React類類型作為其第一個參數,因此如果您嘗試克隆元素,則無法使用。

當然, 還有React.cloneElement() ,它可以對另一個React元素進行深度復制,並且可以選擇提供新的道具。

var foo = React.cloneElement(this.mainContent, {anotherMessage: "nice to meet ya!"});

應該管用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM