javascript - 使用钩子(Hook)设置事件类名

标签 javascript reactjs react-hooks

我正在尝试将我的一些类组件转换为功能组件。
但是我的“toogle”事件类(class)不能使用钩子(Hook),请问我做错了什么,这是我的脚本。

import React from "react";
import "./styles.css";

export default class ActiveState extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activeIndex: 0
    };
  }

  handleOnClick = index => {
    this.setState({ activeIndex: index });
  };

  render() {
    const boxs = [0, 1, 2, 3];
    const box = boxs.map((el, index) => {
      return (
        <button
          key={index}
          onClick={this.handleOnClick.bind(this, index, this.props)}
          className = {this.state.activeIndex === index ? "active" : "unactive"}
        >
          {el}
        </button>
      );
    });
    return <div className="App">{box}</div>;
  }
}
这就是我尝试使用钩子(Hook)但不起作用的方法:
import React, { useState } from "react";
import "./styles.css";

export default function ActiveHooks() {
  const [activeIndex, setActiveIndex] = useState(0);

  const handleOnClick = index => {
    setActiveIndex({ index });
  };

  const boxs = [0, 1, 2, 3];
  const box = boxs.map((el, index) => {
    return (
      <button key={index} onClick={handleOnClick} className= {activeIndex === index ? "active" : "unactive"}>
        {el}
      </button>
    );
  });
  return <div className="App">{box}</div>;
}
提前致谢。

最佳答案

试试这个:

function App() {
  const [activeIndex, setActiveIndex] = React.useState(0);

  const handleOnClick = index => {
    setActiveIndex(index); // remove the curly braces
  };

  const boxs = [0, 1, 2, 3];
  const box = boxs.map((el, index) => {
    return (
      <button
        key={index}
        onClick={() => handleOnClick(index)} // pass the index
        className={activeIndex === index ? "active" : "unactive"}
      >
        {el}
      </button>
    );
  });
  return <div className="App">{box}</div>;
}

ReactDOM.render( <App /> , document.getElementById('root'))
.active {
  background-color: green
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>

关于javascript - 使用钩子(Hook)设置事件类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61377356/

相关文章:

javascript - 如何防止由 onAuthStateChanged Firebase Auth 引起的无限循环

javascript - 如何使用javascript函数设置href参数值

javascript - 图像文件上传的拖放事件在 Aurelia 中不起作用

javascript - React 中的数据从 .CSV 到 JSON 到表(表头也是动态的)

javascript - React 不更新 DOM (Laravel)

react-native - useState 在重新渲染时不断重置为 initialValue

javascript - 如何检查光标是否在文本区域内的空行上?

javascript - 使用 mdsvex 在 Svelte 组件中运行时编译 markdown

javascript - React - 测试 useContext() 调度值

javascript - 如何在不删除数组其余部分的情况下从 React 状态数组中删除组件?