[英]Is there any way to define an element in React that can be used throughout the component?
For example I have the following 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>
)
}
Instead of defining target twice, can I define it once and call it from each event?除了定义目标两次,我可以定义一次并从每个事件中调用它吗?
You can useRef
, but also check recommended approach in second code snippet .您可以
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: 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.