使用挂钩设置活动的className

时间:2020-04-23 00:31:22

标签: javascript reactjs react-hooks

我正在尝试将一些类组件转换为功能组件。 但是我的“ toogle”活动类无法与钩子配合使用,请我做错了什么,这是我的脚本。

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

这是我尝试使用钩子的方法,但是不起作用:

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

提前谢谢。

2 个答案:

答案 0 :(得分:5)

尝试一下:

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>

答案 1 :(得分:0)

  setActiveIndex(index);

除去花括号。例如,如果您单击1,则将钩子更新为{index:1}而不是1。