全部:
我想知道如果我使用无状态组件,如何处理鼠标事件来改变组件样式,例如:
const Com = (props) => {
var hltStyle = false;
function highlight(){
// I do not know what put here
}
var hltStyle = {
backgroundColor: !hltStyle?"lightgreen": "tomato"
}
return (
<div style={hltStyle} onMouseOver={ highlight } >HOVER ME</div>
)
}
我想要的只是悬停此组件并更改背景颜色。高亮内部还有一些其他逻辑,这就是为什么我不能简单地使用CSS
谢谢
最佳答案
你可以使用这样的东西来实现这一点
const Com = () => {
function over(e){
e.target.style.backgroundColor="red";
}
function out(e){
e.target.style.backgroundColor='';
}
return <div onMouseOver={over} onMouseOut={out}>HOVER ME </div>;
}
无论如何,如果您觉得需要声明一些变量以将它们用作状态,则应该使用普通组件而不是无状态组件。
关于reactjs - 如何在React中处理无状态组件中的鼠标事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37690745/