簡體   English   中英

我如何渲染作為帶有附加道具的道具傳入的反應組件?

[英]How do i render a react component passed in as a props with additional props?

我在 Bar 組件中有一個 Foo 組件

import Foo from './foo';    
<Bar component={Foo}>

現在,我想用額外的道具來渲染 this.props.component,foobar = 'LOL';

像這樣的東西

<this.props.component foobar='LOL'/>

我找到了 3 種方法。

克隆

render(){ 
let newFoo = {...this.props.component}
newFoo.props = {...newFoo.props, foobar: 'LOL'}}
return(<div> {newFoo}</div>);}

但我不想克隆。

打回來

render(){ 
!this.props.component.props.foobar&&this.props.addPropsToFoo(foobar: 'LOL');
return(<div> {this.props.component}</div>);

但是,我不想在這種情況下使用回調。

HOC,但我是實習生,這是高級指南。

如果你有一個像

import Foo from './foo';    
<Bar component={Foo}>

你不會在Foo有任何道具,因為你可以渲染組件Foo如下

const Comp = this.props.component;

<Comp foobar='LOL' />

這樣,您也不會克隆組件。

我在 Bar 組件中有一個 Foo 組件

import Foo from './foo';    
<Bar component={Foo}>

需要明確的是,看起來Foo是一個變量,持有對類或函數的引用——換句話說,是一個組件定義,而不是一個組件的實例。 既然如此,您將使用React.createElement創建它的一個實例——事實上,您展示的 JSX 只是此命令的語法糖:

React.createElement(component, props)

您實際上仍然可以為此使用 JSX,您只需要為函數/類使用大寫的變量名,這會通知 Babel 將引用保留為變量而不是將其轉換為類(例如React.createElement(SomeVariable)React.createElement("div") ):

const Example = ({ component: Component }) => 
  <Component otherProps="here" />

同時,當您已經擁有組件的實例時,將使用React.cloneElement

React.render(<Example component={<Foo withProps="here" />, someElement)

const Example = ({ component }) => 
  React.cloneElement(component, { additionalProps: "here" })

您可以將額外的道具傳遞給 Bar 組件

<Bar component={Foo} componentProps={{foobar: 'LOL'}}>

以后可以使用這些道具

<this.props.component foobar={this.props.componentProps.foobar}/>

暫無
暫無

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

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