如何使用useRef改变元素的样式?
How to use useRef to change the style of a element?
我想使用 useRef
挂钩来更改 DOM 元素的样式:
const Box = props => {
const box = useRef(0);
const onClick = () => {
box.current.backgroundColor = "blue";
};
return (
<div>
<div
ref={box}
style={{ width: "300px", height: "300px", backgroundColor: "red" }}
/>
<button onClick={onClick}>Change color of box</button>
</div>
);
};
但是,如果我单击按钮,box
的 backgroundColor
不会改变。
我还创建了一个simple code snippet,它说明了我的问题。
您正在尝试直接在 DOM 元素上修改 non-existent backgroundColor
属性:
box.current.backgroundColor = "blue";
这会(如果有效)将您的 DOM 元素修改为:
<div backgroundColor="blue" ... />
为了使其正常工作,您需要通过 style
属性:
修改 backgroundColor
box.current.style.backgroundColor = "blue";
我想使用 useRef
挂钩来更改 DOM 元素的样式:
const Box = props => {
const box = useRef(0);
const onClick = () => {
box.current.backgroundColor = "blue";
};
return (
<div>
<div
ref={box}
style={{ width: "300px", height: "300px", backgroundColor: "red" }}
/>
<button onClick={onClick}>Change color of box</button>
</div>
);
};
但是,如果我单击按钮,box
的 backgroundColor
不会改变。
我还创建了一个simple code snippet,它说明了我的问题。
您正在尝试直接在 DOM 元素上修改 non-existent backgroundColor
属性:
box.current.backgroundColor = "blue";
这会(如果有效)将您的 DOM 元素修改为:
<div backgroundColor="blue" ... />
为了使其正常工作,您需要通过 style
属性:
backgroundColor
box.current.style.backgroundColor = "blue";