【问题标题】:Add conditional CSS property in React在 React 中添加条件 CSS 属性
【发布时间】:2022-02-02 19:15:56
【问题描述】:

我想以这样一种方式将条件 CSS 属性添加到 div,如果特定条件为真,那么只有它会应用。下面是我的代码。

const Select = ({
  handleClick,
  title,
  permission,
}: SelectProps) => {
  return (
    <div
      onClick={handleClick}
      style={{
        marginTop: '16px',
        cursor: 'pointer',
        pointerEvents   <-- make this property conditional
        ${({ permission }) => permission && `pointerEvents: none;`}  <-- tried this but not working
      }}
    >
      <Title>{title}</Title>
    </div>
  );
};

export const RenderSelectBlock = () => {
  const checkUserPermission = checkUserPermission();
  return (
    <Select
     handleClick={() => setSelectType('Google')}
     title="Google"
     checkUserPermission={checkUserPermission}
    />
    <Select
     handleClick={() => setSelectType('Microsoft')}
     title="Microsoft"
     checkUserPermission={checkUserPermission}
    />
    <Select
     handleClick={() => setSelectType('Apple')}
     title="Apple"
     checkUserPermission={checkUserPermission}
    />
    <Select
     handleClick={() => setSelectType('Facebook')}
     title="Facebook"
     checkUserPermission={checkUserPermission}
    />
  )
);
};

所以在最后一个SelecttitleFacebook,如果用户没有权限,我想禁用它,即permission = false。基本上pointerEvents 属性应该只为title= Facebook 添加,如果permission = false 应该设置为none

【问题讨论】:

    标签: html css reactjs typescript


    【解决方案1】:

    您最好的选择是完全避免使用style 并使用className,然后包含第二类(可能是no-pointer-events)作为您想要选择性包含的pointer-events

    <div
        className={`main-class ${permission ? "no-pointer-events" : ""}`}
    

    但如果你想用style 来做,当你不想指定它时,你可以使用undefined

    <div
        style={{
            marginTop: '16px',
            cursor: 'pointer',
            pointerEvents: permission ? "none" : undefined,
        }}
    

    您还可以在代码中到达这一点之前定义样式对象:

    const style = {
        marginTop: '16px',
        cursor: 'pointer',
    };
    if (permission) {
        style.pointerEvents = "none";
    }
    

    然后使用它:

    <div
        style={style}
    

    有时您会看到人们通过扩展语法对多个属性执行此操作:

    <div
        style={{
            marginTop: '16px',
            cursor: 'pointer',
            ...(permission ? {pointerEvents: "none"} : undefined),
        }}
    

    ...undefined 在对象文字中很好(它不添加任何属性)。

    【讨论】:

      猜你喜欢
      • 2016-12-16
      • 2014-03-18
      • 2018-07-23
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多