You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React如何根据索引设置state变量为true 点击关闭按钮修改对应项状态

React开发问题解决方案

问题2:根据索引设置对应cancel为true,其余为false

你原本的cancel是全局单一布尔值,无法区分不同索引的状态,按需求调整状态结构即可实现:

constructor(){
    super();
    this.state={
        // 存储当前触发关闭的索引,初始-1代表无选中项
        activeCancelIndex: -1
    }
    this.handleClose = this.handleClose.bind(this)
}

handleClose(currentIndex) {
    this.setState({
        activeCancelIndex: currentIndex
    })
}

// 渲染逻辑
<table>
    <tr>
        {
            products.map((val, index)=>{
                // 仅当前索引和存储的激活索引相等时,cancel为true
                const cancel = index === this.state.activeCancelIndex
                return <td key={index}>{val} &nbsp; <button onClick={()=>this.handleClose(index)}>closeIcon</button></td>
            })
        }
    </tr>
</table>

如果需要支持多组独立的cancel状态,可以把state设置为和products长度一致的布尔数组,点击时仅修改对应索引的布尔值即可。


问题1:点击关闭按钮对应值立即变为Fruit

需要把products存入state中,修改时生成新数组触发重渲染即可:

constructor(){
    super();
    this.state={
        products: ['Apple', 'Grapes', 'Pineapples']
    }
    this.handleClose = this.handleClose.bind(this)
}

handleClose(currentIndex) {
    // 拷贝原数组,禁止直接修改state中的引用类型值
    const newProducts = [...this.state.products]
    newProducts[currentIndex] = 'Fruit'
    this.setState({
        products: newProducts
    })
}

// 渲染逻辑
<table>
    <tr>
        {
            this.state.products.map((val, index)=>{
                return <td key={index}>{val} &nbsp; <button onClick={()=>this.handleClose(index)}>closeIcon</button></td>
            })
        }
    </tr>
</table>

内容的提问来源于stack exchange,提问作者Rajendra Bar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 06:15:03