[英]Is there any way to define an element in React that can be used throughout the component?
例如,我有以下組件:
import React from 'react'
export default function App() {
function handleOver() {
const target = document.getElementById("target")
target.style.background = "red"
}
function handleLeave() {
const target = document.getElementById("target")
target.style.background = "green"
}
return (
<div>
<div
id="btn"
onMouseOver={handleOver}
onMouseLeave={handleLeave}>
Test
</div>
<div
id="target">
</div>
</div>
)
}
除了定義目標兩次,我可以定義一次並從每個事件中調用它嗎?
您可以useRef
,也可以在第二個代碼片段中查看推薦的方法。
import React from 'react'
export default function App() {
const target = useRef();
function handleOver() {
target.current.style.background = "red"
}
function handleLeave() {
target.current.style.background = "green"
}
return (
<div>
<div
id="btn"
onMouseOver={handleOver}
onMouseLeave={handleLeave}>
Test
</div>
<div
ref={target}>
</div>
</div>
)
}
But probably it's better not to manipulate the DOM like that yourself , instead define some backgroundColor
state variable with useState
and use style binding like <div style={{backgrondColor: myColorInState}}></div>
or assign a custom CSS class with these colors:
export default function App() {
const [targetColor, setTargetColor] = useState(null);
function handleOver() {
setTargetColor("red");
}
function handleLeave() {
setTargetColor("green");
}
return (
<div>
<div
id="btn"
onMouseOver={handleOver}
onMouseLeave={handleLeave}>
Test
</div>
<div style={{background: targetColor}}></div>
</div>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.