亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在數組中的對象項上設置狀態

如何在數組中的對象項上設置狀態

慕村9548890 2021-11-12 17:44:48
當心形圖標按下它時,我想更新數組對象中關鍵心形的狀態更改為紅色,因此為此我使用了本機圖標,并且在單擊它時使用 heart 和 hearto 進行切換這是代碼:state = {                localAdversiment: [            {              title: "Ecloninear 871",              image: require("../../assets/images/truck_image.png"),              year: "2015",              type: "Truck",              status: "new",              price: "$ 2000",              heart: "hearto"            }這里是按下心臟圖標時調用的函數 handleFavourite = index => {    const { heart } = this.state.localAdversiment[index];    this.setState(      {        heart: "heart"      }    );  };這是心形圖標代碼<TouchableOpacity onPress={() => this.handleFavourite(index)}>                <Icon                  name={item.heart}                  type={"AntDesign"}                  style={{ fontSize: 18 }}                />              </TouchableOpacity>請幫助我如何在單擊時將心更新為心而不是心
查看完整描述

2 回答

?
呼啦一陣風

TA貢獻1802條經驗 獲得超6個贊

您可以通過以下方法輕松完成


state = {      

          localAdversiment: [

            {

              id: 0,

              title: "Ecloninear 871",

              image: require("../../assets/images/truck_image.png"),

              year: "2015",

              type: "Truck",

              status: "new",

              price: "$ 2000",

              heart: "hearto",

              selected: false

            }

}

現在在 onPress 做這個


handleFavourite = (item) => {

   const { id } = item;

   this.setState({

       localAdvertisement: this.state.localAdvertisement.map((item) => {

         if(item.id === id){

           return {

              ...item,

              selected: !item.selected  

           }

         }


         return item


    })

  })

};

現在像這樣渲染


             <TouchableOpacity onPress={() => this.handleFavourite(item)}>

                <Icon

                  name={item.selected ? "heart" : 'hearto'}

                  type={"AntDesign"}

                  style={{ fontSize: 18 }}

                />

              </TouchableOpacity>

希望它會幫助你


查看完整回答
反對 回復 2021-11-12
?
慕尼黑8549860

TA貢獻1818條經驗 獲得超11個贊

編輯此函數如下:


handleFavourite = index => {

    let updatedlocalAdversimentStates = this.state.localAdversiment;

    updatedlocalAdversimentStates[index].heart = "heart";

    this.setState(

      {

        localAdversiment: updatedlocalAdversimentStates

      }

    );

  };


查看完整回答
反對 回復 2021-11-12
  • 2 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號