我正在尝试将我的一些类组件转换为功能组件。
但是我的“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/