Javascript 使用钩子设置活动类名
我正在尝试将我的一些类组件转换为功能组件。 但是我的“toogle”活动类没有使用钩子,请问我做错了什么,这是我的脚本Javascript 使用钩子设置活动类名,javascript,reactjs,react-hooks,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 = {
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>;
}
}
从“React”导入React;
导入“/styles.css”;
导出默认类ActiveState扩展React.Component{
建造师(道具){
超级(道具);
此.state={
活动索引:0
};
}
handleOnClick=索引=>{
this.setState({activeIndex:index});
};
render(){
constboxs=[0,1,2,3];
const box=boxs.map((el,索引)=>{
返回(
{el}
);
});
返回{box};
}
}
这就是我尝试使用钩子但不起作用的地方:
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>;
}
import React,{useState}来自“React”;
导入“/styles.css”;
导出默认函数ActiveHooks(){
常量[activeIndex,setActiveIndex]=useState(0);
const handleOnClick=索引=>{
setActiveIndex({index});
};
constboxs=[0,1,2,3];
const box=boxs.map((el,索引)=>{
返回(
{el}
);
});
返回{box};
}
提前感谢。setActiveIndex(index);
取下花括号。例如,如果单击了1,则将钩子更新为{index:1},而不是1。尝试以下操作:
函数应用程序(){
常量[activeIndex,setActiveIndex]=React.useState(0);
const handleOnClick=索引=>{
setActiveIndex(index);//删除大括号
};
constboxs=[0,1,2,3];
const box=boxs.map((el,索引)=>{
返回(
handleon单击(索引)}//传递索引
className={activeIndex==索引?“活动”:“非活动”}
>
{el}
);
});
返回{box};
}
ReactDOM.render(,document.getElementById('root'))
.active{
背景颜色:绿色
}
谢谢@awran5,它不起作用,我想我应该像这样添加绑定:onClick={handleOnClick.bind(这个,索引)如果使用语法()=>…
但是为什么它不工作?你测试过上面的代码片段吗?你能举个例子吗?这是一个工作原理为什么我必须按两下才能显示颜色?有人知道吗?