简体   繁体   中英

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

I have a Foo component inside Bar component

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

Now, i want to render this.props.component with additional props, foobar = 'LOL';

Something like this

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

I found 3 ways to do it.

Clone

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

But i don't want to clone.

Callback

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

But, i do not want to use callback in this case.

HOC, but i'm intern and this is advanced guide.

If you are having a component like

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

You won't be having any props in Foo because of which you can render the component Foo as below

const Comp = this.props.component;

<Comp foobar='LOL' />

This way you are not cloning the component as well.

I have a Foo component inside Bar component

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

To be clear, it looks like Foo is a variable holding a reference to a class or a function—in other words, a component definition, and not an instance of a component. Since that's the case, you would create an instance of it using React.createElement —in fact, the JSX you show is just syntactic sugar for this command:

React.createElement(component, props)

You can actually still use JSX for this though, you just need to use a capitalized variable name for the function/class, which informs Babel to keep the reference as a variable instead of transforming it into a class (eg React.createElement(SomeVariable) versus React.createElement("div") ):

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

React.cloneElement , meanwhile, is used when you have an instance of a component already:

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

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

You can pass additional props to Bar component

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

Later you can use these props

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM