简体   繁体   中英

Refer to primitive DOM element class

👋

For example, I want to do this:

const DynamicComponent = condition ? MyComponent : React.div;

const usedDynamicComponent = <DynamicComponent> How cool? </DynamicComponent>;

What do I use there instead of React.div , which is a thing I just made up?

const DynamicComponent = condition ? MyComponent : <div>{this.props.children}</div>;

const usedDynamicComponent = <DynamicComponent> How cool? </DynamicComponent>;

You can access the this.props.children to make a layout kind of thing. You can access the child of some component inside itself by using this.props.children .

class Div extends Component {
  render() {
    return <div {...this.props} >{this.props.children}</div>;
  }
}

This will wrap anything you put inside the Div tag between the HTML div tag. To access the props of the component given to the <Div> , you can simply add {...this.props} , it will add all your props on the actual div .

You can use the above-given component like:

<Div className="custom" custom_prop="value"><AnyReactComponent /></Div>

will convert to:

<div className="custom" custom_prop="value"><AnyReactComponent /></div>

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