简体   繁体   English

如何在 React 的无状态组件中处理鼠标事件

[英]How to handle mouse event in stateless component in React

All:全部:

I wonder if I use stateless component, how can I handle mouse event to change component style, for example:我想知道如果我使用无状态组件,我如何处理鼠标事件来改变组件样式,例如:

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>
    )
}

What I want just hover this component and change background color.我想要的只是悬停此组件并更改背景颜色。 There is some other logic inside highlight, that is why I can not simply use CSS高亮内部还有一些其他逻辑,这就是为什么我不能简单地使用 CSS

Thanks谢谢

You can achieve that using something like this 你可以用这样的东西来实现

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>;
}

Anyway, if you feel that you need to declare some variables to use them as the state, you should use a normal component instead of a stateless one. 无论如何,如果你觉得你需要声明一些变量来将它们用作状态,你应该使用普通组件而不是无状态组件。

jsfiddle 的jsfiddle

What about using classic CSS for simple hover effects?将经典 CSS 用于简单的悬停效果怎么样?

    <div class="el-to-hover"></div>

    //somewhere in css-file:

    .el-t-hover {
       background: transparent
       transition: background .3s ease-in-out;
    }
    .el-to-hover:hover {
       background: red
    }

done完毕

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM