简体   繁体   English

react.js 中的 hover 按钮

[英]a hover button in react.js

i would like to ask how to make a button but when the mouse is on the button (hover),the new button is displayed above the previous button... and it's in react.js.. thx我想问一下如何制作一个按钮,但是当鼠标在按钮上(悬停)时,新按钮显示在前一个按钮上方......并且它在react.js .. thx

this is the way of my code..这是我的代码的方式..

var Category = React.createClass({displayName: 'Category',
  render: function () {
      return (
        React.createElement("div", {className: "row"}, 
        React.createElement("button", null, "Search",   {OnMouseEnter://I have no idea until here})
      )
    );
  }
});

React.render(React.createElement(Category), contain);

If I understand correctly you're trying to create a whole new button.如果我理解正确,您正在尝试创建一个全新的按钮。 Why not just change the label/style of the button as @André Pena suggests?为什么不像@André Pena 建议的那样更改按钮的标签/样式?

Here is an example:下面是一个例子:

var HoverButton = React.createClass({
    getInitialState: function () {
        return {hover: false};
    },

    mouseOver: function () {
        this.setState({hover: true});
    },

    mouseOut: function () {
        this.setState({hover: false});
    },

    render: function() {
        var label = "foo";
        if (this.state.hover) {
            label = "bar";
        }
        return React.createElement(
            "button",
            {onMouseOver: this.mouseOver, onMouseOut: this.mouseOut},
            label
        );
    }
});

React.render(React.createElement(HoverButton, null), document.body);

Live demo: http://jsfiddle.net/rz2t224t/2/现场演示: http : //jsfiddle.net/rz2t224t/2/

You should probably just use CSS for this, but if you insist on doing it in JS you simply set flag in state to true in your onMouseEnter, and set the same flag to false in onMouseLeave.您可能应该为此使用 CSS,但如果您坚持在 JS 中执行此操作,您只需在 onMouseEnter 中将 state 中的标志设置为 true,并在 onMouseLeave 中将相同的标志设置为 false。 In render you render the other button if the flag is true.在渲染中,如果标志为真,则渲染另一个按钮。

Nothing fancy or complicated involved.没有什么花哨或复杂的事情。

I'm not sure when you would like to show a first button (above) only when the second button is hovered.我不确定您何时只在第二个按钮悬停时才显示第一个按钮(上图)。 If the mouse hover is removed from the second button the first button would be disappear again.如果鼠标悬停从第二个按钮上移除,第一个按钮将再次消失。 But I guess the question was to show it and also make it interactable.但我想问题是要展示它并使其可交互。

In React you would use the state for that.在 React 中,你会为此使用状态。 In a functional React component the useState hook is the best option.在功能性 React 组件中, useState钩子是最好的选择。 The onMouseOver event on the button changes the state variable on hover by calling the setShowButtons function.按钮上的onMouseOver事件通过调用setShowButtons函数更改悬停时的状态变量。 I usually toggle CSS classes based on the variable ( showButtons in this example) but one could also use conditional render as button #3 in the this example.我通常根据变量(在本例中为showButtons )切换 CSS 类,但在本例中也可以使用条件渲染作为按钮 #3。

Showing button #1 above when button #2 is hovered is also possible with only CSS.仅使用 CSS 也可以在按钮 #2 悬停时显示上面的按钮 #1。 In this example with flex-box (reversing the order of the two buttons) and the sibling selector (~).在这个带有 flex-box(颠倒两个按钮的顺序)和同级选择器 (~) 的示例中。

 const App = () => { const [showButtons, setShowButtons] = React.useState(false); return ( <main className="main-container"> <h4>Show buttons with React state</h4> <button className={showButtons ? "button" : "button _hide"}> #1. I'm shown with a CSS transition when #2 is hovered </button> <button className="button" onMouseOver={() => setShowButtons(true)} onFocus={() => setShowButtons(true)} onMouseOut={() => setShowButtons(false)} onBlur={() => setShowButtons(true)} > #2. Hover me to show #1 and #3 button </button> {showButtons && ( <button className="button"> #3. I'm rendered when #2 is on hovered </button> )} <hr /> <h4>Show button with CSS only</h4> <div className="reversed-container"> <button className="button-2">#2. Hover me to show button #1</button> <button className="button-2 _hide"> #1. I'm shown with a CSS transition when #2 is hovered </button> </div> </main> ); }; ReactDOM.render(<App />, document.getElementById("root"));
 .main-container { display: flex; flex-direction: column; } .reversed-container { display: flex; flex-direction: column-reverse; } hr { width: 100%; margin-top: 1rem; } .button, .button-2 { padding: 1rem; transition: opacity 1s; } .button._hide, .button-2._hide { opacity: 0; pointer-events: none; } .button:hover, .button-2:hover { opacity: 1; pointer-events: initial; background-color: lightyellow; } .button-2:hover ~ .button-2._hide { opacity: 1; pointer-events: initial; background-color: lightyellow; }
 <script src="https://unpkg.com/react/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script> <div id="root"></div>

Here is my Solution for the Functional Based Components.这是我的基于功能的组件的解决方案。 I'm assuming that you're looking to change the colour of the button on the "mouse hover" event.我假设您正在寻找更改“鼠标悬停”事件按钮的颜色。 You can use anything by following my code though.不过,您可以按照我的代码使用任何东西。

Please import useState and useEffect hook as请导入 useState 和 useEffect hook as

import React, { useState, useEffect } from 'react';

Now, Make the state as:-现在,将状态设为:-

const [hover, setHover] = useState(false);

Define the colour that you want to render on Mouse Hover, I'm defining primary colour and mouseOverColor here.定义要在鼠标悬停上渲染的颜色,我在这里定义原色和 mouseOverColor。

let primaryColor:red
let mouseOverColor:blue

Now in JSX of Reactjs.现在在 Reactjs 的 JSX 中。

return (<div>

<Button
      
      style={backGroundColor: hover === true ? mouseOverColor : primaryColor}
      onMouseOver={(e) => {
        e.preventDefault();
        setHover(true);
      }}
      onMouseLeave={(e) => {
        e.preventDefault();
        setHover(false);
      }}
    >
      Say hi
    </Button>

</div>)

Please make sure to use useEffect dependency with the "hover" property so it should refresh background colour whenever the component gets mouseover effect as:-请确保将 useEffect 依赖项与“hover”属性一起使用,以便在组件获得鼠标悬停效果时刷新背景颜色:-

  useEffect(() => {}, [hover]);

Note:- I use button of Material UI, you can use plain HTML button too.注意:- 我使用 Material UI 的按钮,你也可以使用纯 HTML 按钮。

import { Button } from '@material-ui/core';

RESULT:- Norammly button would be Red and on Mouse Hover , it should be red and vice versa.结果:- 正常按钮将是红色的,在鼠标悬停时,它应该是红色的,反之亦然。 That's pretty much it.差不多就是这样。

easy & simple way to do this with hooks:使用钩子简单而简单的方法:

import React, { useState } from "react";

export default function App() {
  const [hover, setHover] = useState(false);

  const handleMouseIn = () => {
    setHover(true);
  };

  const handleMouseOut = () => {
    setHover(false);
  };

  return (
    <div>
      <button onMouseOver={handleMouseIn} onMouseOut={handleMouseOut}>
        {hover ? "foo" : "bar"}
      </button>
    </div>
  );
}

we have the hover state to track whether we hovered over the button or not.我们有hover state 来跟踪我们是否将鼠标悬停在按钮上。 we set it to true in handleMouseIn and false in handleMouseOut .我们在handleMouseOut中将其设置为 true,在handleMouseIn中将其设置为 false。 we set onMouseOver to handleMouseIn and onMouseOut to handleMouseOut .我们将onMouseOver设置为handleMouseIn并将onMouseOut设置为handleMouseOut

This way, hover is true when we hovered over the button and false otherwise.这样,当我们将鼠标悬停在按钮上时,hover 为真,否则为假。

I just read some tutorials about react.js, and I found this solution.我刚刚阅读了一些关于 react.js 的教程,我找到了这个解决方案。

For the sake of reusability, and to separate out the "hover" logic, you can create a component to replace your normal tag.为了可重用性,并分离出“悬停”逻辑,您可以创建一个组件来替换您的普通标签。

Something like this:像这样的东西:

var React = require('react');
var classNames = require('classnames');
var HoverHandlers = require('./HoverHandlers.jsx');

var ElementHover = React.createClass({
  mixins: [HoverHandlers],

  getInitialState: function () {
    return { hover: false };
  },

  render: function () {
    var hoverClass = this.state.hover ? this.props.hoverClass : '';
    var allClass = classNames(this.props.initialClasses, hoverClass);

    return (
      <this.props.tagName 
                          className={allClass} 
                          onMouseOver={this.mouseOver} 
                          onMouseOut={this.mouseOut}>
        {this.props.children}
      </this.props.tagName>
    );
  }

});

module.exports = ElementHover;

The HoverHandlers mixin is like (you can also add handlers for :active :focus, etc...): HoverHandlers mixin 就像(你也可以为 :active :focus 等添加处理程序......):

var React = require('react');

var HoverHandlers = {
  mouseOver: function (e) {
    this.setState({ hover: true });
  },
  mouseOut: function (e) {
    this.setState({ hover: false });
  },
};  
module.exports = HoverHandlers;

You then can use the component like this:然后,您可以像这样使用该组件:

<ElementHover tagName="button" hoverClass="hover" initialClasses="btn btn-default" >
          Label or content of the button
</ElementHover>

The code might need to be optimized.代码可能需要优化。 So, many thanks to anyone can help me about that.所以,非常感谢任何人可以帮助我。

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

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