React 中有多种方法可以操作和设置 HTML 元素的样式(通常不使用 getElementbyId、querySelector 或任何其他 Document 方法。)
正如 Kasper 在他的回答中提到的那样
每个传入 onClick 属性的函数都有一个事件。
所以你可以很容易地从点击事件中获取目标来访问 HTML 元素。
import React from "react"
const MyComponent = () => {
const changeColor = e => {
e.target.style.color = "green"
}
return <button onClick={changeColor}>Hello World</button>
}
export { MyComponent }
也许您不想操作按钮本身,而是要操作另一个 HTML 元素。 Refs 可能是实现此目的的一种方式,但 the React docs suggest to avoid this if you can do it declaratively.
import React, { useRef } from "react"
const MyComponent = () => {
const myRef = useRef()
const handleClick = () => {
myRef.current.style.color = "green"
}
return (
<div>
<button onClick={handleClick}>Hello World</button>
<p ref={myRef}>Hello world!</p>
</div>
)
}
export { MyComponent }
在某个阶段,您的组件将达到需要使用状态来跟踪事物的程度。
在这种情况下,我们倾向于不直接操作 HTML 元素,而是允许 HTML 元素反映我们状态中的值。
import React, { useState } from "react"
const MyComponent1 = () => {
const [colorIndex, setColorIndex] = useState(0)
const myColors = [
"fuchsia",
"cornflowerblue",
"firebrick",
"deepskyblue",
"MediumAquamarine",
"goldenrod",
"OliveDrab",
"darkmagenta",
"orangered",
]
const handleClick = () => {
setColorIndex(colorIndex >= myColors.length - 1 ? 0 : colorIndex + 1)
}
return (
<button style={{ color: myColors[colorIndex] }} onClick={handleClick}>
Hello World
</button>
)
}
export { MyComponent }
如果您还没有,现在可能是查看 React 文档的好时机,尤其是 Thinking in React。