一种在其他按钮上使用 useReducer 函数的方法

A way to use useReducer function on other buttons

我是 React.js 的新人。我想再次传递相同的行为,但在其他两个按钮上就像我在第一个按钮上所做的那样。

我开始使用以下函数来传递我的 useReducer:

const hoverReducer = (state, action) => {
let newState;
switch (action.type) {
    case 'true':
        newState = {
            transform: `scale(1.08)`,
            backgroundColor: "transparent",
            border: "none",
            transition: `all 0.3s ease-in.out`
        }
        break;
    case 'false':
        newState = {
            transform: `scale(1.0)`,
            backgroundColor: "transparent",
            border: "none",
        }
        break;
    default:
        throw new Error();
    }
    return newState;
}

然后在我的函数 Primary() 中我这样做了:

const initialState = {
    transform: `scale(1.0)`,
    backgroundColor: "transparent",
    border: "none"
}

const [buttonStyle, setButtonStyle] = useReducer(hoverReducer, initialState)



const addHover = ()=>{
    setButtonStyle({type: 'true'})
}
const removeHover = () =>{
    setButtonStyle({type: 'false'})

}

我的return:

    return (
    <div>
        <button style={buttonStyle} onMouseEnter={() => addHover()}
            onMouseLeave={() => removeHover()}
        >
            <img src="https://i.ibb.co/mJ6fzbt/gm-c.png" border="0" style={styleImg} />
        </button>
        <button >
            <img src="https://i.ibb.co/znbBNmX/link-c.png" border="0" style={styleImg} />
        </button>
        <button >
            <img src="https://i.ibb.co/HXXjyPT/twi-c.png"  border="0" style={styleImg} />
        </button>

    </div>
)

提前致谢。

您应该创建一个具有悬停逻辑的新组件,这样您创建的每个按钮都包含该逻辑。并接受图像的 src URL 以及您需要的任何东西作为道具。

我的按钮

const MyButton = ({ styleImg, src }) => {
  const initialState = {
    transform: `scale(1.0)`,
    backgroundColor: "transparent",
    border: "none"
  };

  const [buttonStyle, setButtonStyle] = useReducer(hoverReducer, initialState);

  const addHover = () => {
    setButtonStyle({ type: "true" });
  };
  const removeHover = () => {
    setButtonStyle({ type: "false" });
  };

  return (
    <button
      style={buttonStyle}
      onMouseEnter={() => addHover()}
      onMouseLeave={() => removeHover()}
    >
      <img src={src} border="0" style={styleImg} />
    </button>
  );
};

应用程序

export default function App() {
  return (
    <div>
      <MyButton src="https://i.ibb.co/mJ6fzbt/gm-c.png" styleImg={""} />
      <MyButton src="https://i.ibb.co/znbBNmX/link-c.png" styleImg={""} />
      <MyButton src="https://i.ibb.co/HXXjyPT/twi-c.png" styleImg={""} />
    </div>
  );
}