Ted*_*ppe 3 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>;
}
}
Run Code Online (Sandbox Code Playgroud)
这就是我尝试使用钩子的方法,但不起作用:
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>;
}
Run Code Online (Sandbox Code Playgroud)
提前致谢。
尝试这个:
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'))Run Code Online (Sandbox Code Playgroud)
.active {
background-color: green
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4440 次 |
| 最近记录: |