![](/img/trans.png)
[英]When using react-router, is there a different way to pass props from a stateful component to a stateless one
[英]React clone component (stateless or stateful) to pass additional props
我想克隆/擴展一個React組件(不知道它是有狀態的還是無狀態的)並傳遞它的道具:
const Foo = (props) => {
return (
<div>foo</div>
);
}
class Bar extends React.Component {
render() {
return (
<div>bar</div>
)
}
}
問題是,應該對Foo
和Bar
這兩個變量進行不同的處理:
const FooExtended = (props, context) => {
return Foo(_.extend(props, additionalProps), context);
}
class BarExtended extends Bar {
constructor(props, context) {
super(_.extend(props, additionalProps), context);
}
}
沒有簡單的方法來知道變量Component
是Stateless還是Statefull,而無需進行駭人的toString
regex測試。
React.cloneElement/createElement
在這些失敗,給我以下錯誤:
React.createElement:類型無效-預期為字符串(對於內置組件)或類/函數(對於復合組件),但得到了:對象。 您可能忘記了從定義文件中導出組件。
那么,有什么簡單的方法可以只做cloneComponent(originalComponent, additionalProps)
嗎?
沒有簡單的方法來知道變量Component是無狀態還是有狀態[...]
而且我認為這是為什么需要extend React.Component
的原因之一,以便更容易地區分兩者。 因為React本身必須能夠區分它們,因為如果沒有new
則無法實例化es class
。
您可以執行以下操作:
function cloneComponent(originalComponent, additionalProps) { if (originalComponent.prototype instanceof React.Component) { return class extends originalComponent { constructor(props, context) { super(_.extend(props, additionalProps), context); } }; } return (props, context) => { return originalComponent(_.extend(props, additionalProps), context); }; }
因為Foo.protoype instanceof React.Component
是true
。
但是 ,我認為更常見的做法是執行以下操作:
function addProps(Component, additionalProps) {
return props => <Component {...props} {...additionalProps} />;
}
這樣就無需區分有狀態組件和無狀態組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.