为了账号安全,请及时绑定邮箱和手机立即绑定

onClick 函数不会删除数组中的项目

onClick 函数不会删除数组中的项目

PIPIONE 2023-04-27 16:39:54
我有一个按钮,当您单击它时应该从列表中删除一个框,但它不起作用。谁能明白为什么?const Box = (props) => {    return (        <>            <div id={props.id} style={{height:`${props.height}em`, width:`${props.width}em`, backgroundColor: props.color }}>             </div>           <Button onClick={props.removeItem}/>        </>    );};export default Box;const BoxList = () => {const [boxes, setBoxes] = useState([{height: "", width:"", color:"", id:""}]);const removeBox = (boxId) => {   const updatedBoxList = boxes.filter(box => box.id !== boxId);    setBoxes(updatedBoxList);  // this is where the update should happen};const boxesArray = boxes.map((box) => {    return(    <Box width={box.height}         height={box.width}         color={box.color}         id={box.id}         removeItem={removeBox}    />    )});[...]
查看完整描述

2 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

const Box = (props) => {

    const removeItem = () => {

        props.removeItem(props.id);

    };

    return (

        <>

            <div id={props.id} style={{height:`${props.height}em`, width:`${props.width}em`, backgroundColor: props.color }}>

             </div>

           <Button onClick={removeItem}/>

        </>


    );

};

export default Box;

我已经重新定义了您的 Box 组件,以便它使用props.removeItem函数期望的参数调用函数


查看完整回答
反对 回复 2023-04-27
?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

您需要将 boxId 传递给 removeItem。现在它以点击事件作为参数被调用。



查看完整回答
反对 回复 2023-04-27
  • 2 回答
  • 0 关注
  • 69 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信