【发布时间】: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.CSSProperties:const 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