繁体   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