【问题标题】:How to inject JavaScript inside JSX attribute's string? [closed]如何在 JSX 属性的字符串中注入 JavaScript? [关闭]
【发布时间】:2021-11-07 11:25:14
【问题描述】:

我正在尝试将一些默认道具放入 className=" px-6 py-2 bg-black rounded-full text-black " 当我在其他地方使用这个组件时,我会将背景或文本颜色作为道具传递。

这种操作的正确语法是什么?

我试图在经典的 ${} 中使用重音 `,但它在我的 react 应用程序中不起作用。

<button className=`btn px-6 py-2 bg-${} rounded-full`>
  shop
</button>

【问题讨论】:

标签: javascript reactjs jsx


【解决方案1】:

您将使用 JSX 表达式,即 {expression}(在 JSX 上下文中)。所以你可能会在{} 中使用模板文字,就像这样(假设backgroundColortextColor 包含道具):

return (
    <Button className={`px-6 py-2 bg-${backgroundColor} text-${textColor}`}>
        ...
    </Button>
);

不一定是模板字面量,也可以是字符串拼接表达式:

return (
    <Button className={"px-6 py-2 bg-" + backgroundColor + " text-" + textColor}>
        ...
    </Button>
);

或者为了避免 JSX 难以使用,请在 JSX 之前完成:

const theClass = `px-6 py-2 bg-${backgroundColor} text-${textColor}`;
return (
    <Button className={theClass}>
        ...
    </Button>
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 2018-01-30
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 2017-01-03
    相关资源
    最近更新 更多