首页 > 解决方案 > 为什么 onClick 处理程序不更改图标标签的类名?

问题描述

每当我单击具有与其链接的 onClick 处理程序的方形图标时,它不会更改该图标的类名。

在图标标签内如果 box.isChecked === true 那么我想显示“far fa-check-square icon”的类
名,但如果 box.isChecked === false 那么我想显示“far fa-square icon”的类名” 。但它不起作用。

应用 js 文件:

import React , {useState} from 'react'
const data = [
{
    id:0,
    para:"This is Box One",
    isChecked:false
},
{
    id:1,
    para:"This is Box Two",
    isChecked:false
},
{
    id:2,
    para:"This is Box Three",
    isChecked:false
},
{
    id:3,
    para:"This is Box Four",
    isChecked:false
}];


const App = () => {
let [list,setList] = useState(data);

const checked = (id) => {
    for(let i = 0;i < list.length;i++){
        if(i === id){
            if(list[i].isChecked === false){
                list[i].isChecked = true;
                break;
            }else{
                list[i].isChecked = false;
                break;
            }
        }
    }
    let newList = list;
    console.log(newList);
    setList(newList);
}

return(
    <>
        {list.map((box) => {
            return (
                <div className="box" key={box.id}>
                    <i className={box.isChecked === true ? "far fa-check-square icon":"far fa-square icon"} onClick={() => checked(box.id)}> </i>
                    <p className="para"> {box.para} </p>
                </div>
            )
        })}
    </>
)}
export default App;

索引 js 文件:

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import './index.css'
ReactDOM.render(<App />,document.getElementById("root"));

索引 css 文件:

*{
margin:0px;
padding:0px;
box-sizing:border-box;
}
.box{
width:250px;
padding:15px;
margin:0px 0px 15px 0px;
background-color:rgb(81, 162, 255);
}
.icon{
font-size:25px;
cursor:pointer;
color:white;
margin:0px 0px 5px 0px;
}
.para{
font-size:20px;
font-family:arial;
color:white;
}

标签: javascripthtmlreactjstypescriptreact-native

解决方案


在此代码块中,您不会更改对数组的引用,只是更改值。setState除非值引用更改,否则不会触发重新渲染。

const checked = (id) => {
    for(let i = 0;i < list.length;i++){
        if(i === id){
            if(list[i].isChecked === false){
                list[i].isChecked = true;
                break;
            }else{
                list[i].isChecked = false;
                break;
            }
        }
    }
    let newList = list; // <-- you are not creating a new array here.
    console.log(newList);
    setList(newList);
}

要解决此问题,您可以使用更新的值克隆数组。

setList([...list]);

推荐阅读