【问题标题】:Having css property in variable in react hooks在反应钩子中具有变量中的css属性
【发布时间】:2020-10-29 04:31:27
【问题描述】:

我需要删除 html 元素的一些属性,并根据一些事件添加一些额外的属性。 我试图通过为所需的 css 属性创建一个对象变量并尝试在运行时通过将新的对象值分配给 css 变量来更改它来实现这一点。

这里是示例代码:

const MyCssVariableSample = (props) => {
  const [testCssVariable, setTestCssVariable] = useState({
    height: "100%",
    width: "100%",
    color: "purple",
  });

  return (
    <div>
      <h1>Welcome</h1>
      <button
        onClick={() => {
          setTestCssVariable({
            position: "absolute",
            bottom: "0",
            right: "0",
            color: "purple",
          }),
        }}
      >Hello there</button>
      <div className="xyz">
        <video id="abc" style={testCssVariable} />
      </div>
    </div>
  );
};

但我不能这样做,因为代码允许我更改已定义键的值但不引入键,所以在这种情况下,如果我想更改高度、宽度或颜色,那很好,但我无法引入位置、边距或任何其他新键。

这是错误:

'{ position: string; 类型的参数底部:字符串;右:字符串;颜色:字符串; }' 不可分配给 'SetStateAction'。输入'{位置:字符串;底部:字符串;右:字符串;颜色:字符串; }' 缺少来自类型 '{ height: string; 的以下属性;宽度:字符串;颜色:字符串; “背景色”:字符串;位置:字符串;底部:字符串;右:字符串; }':高度,宽度,“背景颜色”

我怎样才能达到同样的效果?我对反应和钩子很陌生。

【问题讨论】:

  • 正如有人已经提到的那样,额外的逗号会产生语法错误,但否则此代码可以正常工作。
  • 这是我得到的错误:Argument of type '{ position: string;底部:字符串;右:字符串;颜色:字符串; }' 不可分配给 'SetStateAction'。输入'{位置:字符串;底部:字符串;右:字符串;颜色:字符串; }' 缺少来自类型 '{ height: string; 的以下属性;宽度:字符串;颜色:字符串; “背景色”:字符串;位置:字符串;底部:字符串;右:字符串; }':高度,宽度,“背景颜色”
  • 这是一个打字稿问题,不是反应问题。尝试在声明样式对象后添加as React.CSSPropertiesconst style = { position: 'absolute'} as React.CSSProperties
  • 或者,尝试将您的代码作为 vanilla js 运行。那样它就可以正常工作了。
  • @M-N 谢谢,这有帮助!一个问题,我尝试将普通变量创建为 React.CSSProperties 并且它按预期工作。但不知何故,它不适用于我使用钩子初始化的变量。我想知道,如何做到这一点! const remoteVideoTileStyle = { "background-color": "yellow", color: "yellow", display: "none", height: "100%", width: "100%", } as React.CSSProperties;这行得通。但下面没有。 const [localVideoTileStyle, setLocalVideoTileStyle] = useState({...}) as React.CSSProperties;

标签: css reactjs react-hooks use-state


【解决方案1】:

这里有错别字,

        onClick={() => {
          setTestCssVariable({
            position: "absolute",
            bottom: "0",
            right: "0",
            color: "purple",
          }), // <- ','
        }}

除此之外,一切正常,并且该职位在我的测试中得到应用,纠正错字后再次检查

【讨论】:

  • 嗨@aXuser264,感谢您的快速回复,但这不是错字,我有两个这样的变量,在粘贴代码时,我删除了一个以使问题清晰而忘记删除“,”。如果可能的话,你能粘贴你测试的代码吗?
  • @tv1902 其他一切看起来都很干净,我刚刚删除了那个错字,一切正常,请给沙箱快速找到问题!
  • 如果有帮助,这是错误:Argument of type '{ position: string;底部:字符串;右:字符串;颜色:字符串; }' 不可分配给 'SetStateAction'。输入'{位置:字符串;底部:字符串;右:字符串;颜色:字符串; }' 缺少来自类型 '{ height: string; 的以下属性;宽度:字符串;颜色:字符串; “背景色”:字符串;位置:字符串;底部:字符串;右:字符串; }':高度,宽度,“背景颜色”
  • @tv1902 嘿,全是乱码,你能把它添加到问题中吗
  • @tv1902 我无法从该示例中捕获任何内容,请提供任何实时沙箱??
猜你喜欢
  • 2019-08-21
  • 2015-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多