简体   繁体   English

createElement 设置 HTML 标签有条件地反应 JS

[英]createElement set HTML tag conditionally React JS

Consider this:考虑一下:

const Component = React.createElement(props.type ? "p" : "div", {
    className: "fff"
})

How do I set HTML tag conditionally (one line)?如何有条件地设置 HTML 标签(一行)?

Or, if its possible, right inside JSX (something like that):或者,如果可能的话,就在 JSX 内部(类似的东西):

<props.type ? "p" : "div" />

If you're using jsx then I would just recommend doing it in your component.如果您使用的是 jsx,那么我建议您在您的组件中使用它。

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.如果您有共同的内容,只需将其存储在 const 某处,并将其插入标签之间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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