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

我有一个按钮,当您单击它时应该从列表中删除一个框,但它不起作用。谁能明白为什么?


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}

    />

    )

});

[...]


PIPIONE
浏览 86回答 2
2回答

慕码人8056858

const Box = (props) => {&nbsp; &nbsp; const removeItem = () => {&nbsp; &nbsp; &nbsp; &nbsp; props.removeItem(props.id);&nbsp; &nbsp; };&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div id={props.id} style={{height:`${props.height}em`, width:`${props.width}em`, backgroundColor: props.color }}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<Button onClick={removeItem}/>&nbsp; &nbsp; &nbsp; &nbsp; </>&nbsp; &nbsp; );};export default Box;我已经重新定义了您的 Box 组件,以便它使用props.removeItem函数期望的参数调用函数

至尊宝的传说

您需要将 boxId 传递给 removeItem。现在它以点击事件作为参数被调用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript