Consider this:
const Component = React.createElement(props.type ? "p" : "div", {
className: "fff"
})
How do I set HTML tag conditionally (one line)?
Or, if its possible, right inside JSX (something like that):
<props.type ? "p" : "div" />
If you're using jsx then I would just recommend doing it in your component.
const Component = (props) => {
const content = // whatever content you want
return props.type ? (
<p>
{content}
</p>
) : (
<div>
{content}
</div>
);
};
This will conditionally return what you want, you can do all sorts of stuff with this kind of syntax and at this level.
Or if it's not a specific component and just in code, the same thing applies.
{props.type ? (
// code for <p>
) : (
// code for <div>
)
If you have common content, just store that in a const somewhere, and insert it between the tags.
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.