在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML/ react 怎么控制循環(huán)輸出的checkbox復(fù)選框的checked屬性?

react 怎么控制循環(huán)輸出的checkbox復(fù)選框的checked屬性?

請(qǐng)問(wèn) react 中怎么控制循環(huán)輸出的 checkbox 的 checked 屬性?定義state狀態(tài)的時(shí)候該怎么定義?
我目前是在state中定義了一個(gè)空數(shù)組 checked, 然后在 componentWillMount 和 componentWillReceiveProps 中根據(jù)循環(huán)的個(gè)數(shù)對(duì)數(shù)組 checked 進(jìn)行了賦值,用于循環(huán)控制 dom 中的 checkbox,代碼如下:

 constructor(props) {
    super(props);
    this.state = {
      checked: []
    };
  }
componentWillReceiveProps(nextProps) {
    const { dispatch, organization, model } = nextProps;
    if (this.state.showCreateModal) {
      dispatch({ type: 'createProjectModal/fetch', payload: organization })
    }
    
    // ***根據(jù)循環(huán)出的 checkbox 個(gè)數(shù)對(duì) checked 進(jìn)行賦值
    if (model.members.length > 0) {
      let arr = model.members.filter(item => item.user_id !== auth.getUser().user_id);
      let checked = [];
      arr.forEach(item => {
        let obj = {};
        obj[`${item.user_id}`] = false;
        checked.push(obj)
      });
      this.setState({ checked })
    }
  }

然后 dom 中,直接一一對(duì)應(yīng):

<ul>
        {members.length > 0 && members.map(item => {
          let index = null;
          for(let i = 0; i < checked.length; i++) {
            if (checked[i] === item.user_id) {
              index = i;
              return index
            }
          }
          return (<li key={item.user_id}>
            <input
              type="checkbox"
              checked={checked[index]}        // ***對(duì)應(yīng)state中的控制元素??
              ref={(e) => {this.checkboxRef[item.user_id] = e}}
              value={item.user_id}
              onChange={(e) => {this.onSelectChange(item, e)}} 
            />
          </li>)
        })}
      </ul>

然后在復(fù)選框的 onChange 函數(shù)中,根據(jù)是否勾選 改變 state 中 checked 的狀態(tài):

if (e.target.checked){
  checked[index] = true;    // 勾選的話 將狀態(tài)改為 true
} else {
  checked[index] = false;   // 取消勾選 將狀態(tài)改為 false
}

但是 當(dāng)我運(yùn)行的時(shí)候,會(huì)報(bào)下面這個(gè)錯(cuò)誤:
圖片描述

我知道這應(yīng)該是 componentWillMount 的時(shí)候 checked 為空,所以 checkbox 為不受控組件(checked 屬性沒(méi)有起作用),componentWillReceiveProps 之后 checked 不為空,所以對(duì)復(fù)選框又變成了受控組件,應(yīng)該是這個(gè)原因,但是我不知道該怎么解決??求大神告知一個(gè)思路?

回答
編輯回答
別傷我

嘗試將input里的checked屬性改為

checked={checked[index] || false}

另外我覺(jué)得這個(gè)ckecked應(yīng)該放在members這個(gè)數(shù)組里比較好,不然這樣對(duì)應(yīng)還是很容易出問(wèn)題的??紤]改下數(shù)據(jù)結(jié)構(gòu)

2017年5月12日 05:28