【问题标题】:update checkbox isChecked stauts in parent更新复选框在父项中处于选中状态
【发布时间】:2020-08-26 21:34:49
【问题描述】:

父组件

class Parent extends Component {
 constructor(props) {
        super(props);
        this.state = {
        checkedView:[
                {id: 1, value: "A", isChecked: false},
                {id: 2, value: "B", isChecked: true},
                {id: 3, value: "C", isChecked: true},
                {id: 4, value: "D", isChecked: true}
            ],
        }
    }
   handleCheck=(e)=>{
       this.setState({ isChecked: e.target.checked});
   }
   render(){
     return(
        <div>
             <Selection checkedView={this.state.checkedView} handleCheck={this.handleCheck} />
             <Content checkedView={this.state.checkedView} />
        </div>
     );
   }
}

选择组件

class Selection extends Component {
  constructor(props) {
    super(props)
    this.state = {
      checkedView: this.props.checkedView
    }
  }

  handleCheck = (event) => {
    let checkedView = this.props.checkedView;
      checkedView.forEach( item => {
        if(item.value === event.target.value){
          item.isChecked = event.target.checked
        }
      })
    this.setState({
      checkedView: checkedView
    })
    this.props.handleCheck(event)
  }  

  render() {
    return (
      <div className="">
        <ul className="morefeatures">{
          this.props.checkedView.map((selection, index) => {
            return (<CheckBox  key={index} handleCheck={this.handleCheck} {...selection}  />)
          })
        }
        </ul>
      </div>
    );
  }
}

复选框

export const CheckBox = props => {
    return (
      <li>
       <input key={props.id} onClick={props.handleCheck} type="checkbox" checked={props.isChecked} value={props.value} /> {props.value}
      </li>
    )
}

我有一个控制内容的父组件,并且选择组件应该能够更新其对父组件的更改,以便其他子组件可以访问复选框的值。 当检查(或多个)复选框时,内容组件接收信号以显示相关内容,类似于该相关内容

无论复选框被选中还是未选中,isChecked 都不会改变其状态。

那么我应该如何修改代码才能让isChecked真正起作用??????

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您没有更新正确的状态。 this.setState({ isChecked: e.target.checked}); 向状态添加了一个新变量 isChecked。您想要的是在checkedView 中找到正确的条目并更新该对象。我会将id 传递给复选框,在onClick 上,我会调用handleChecked,它不仅接收事件,还接收复选框的id。然后在handleChecked 中,您可以根据id 找到正确的复选框并相应地更新该复选框。

    在父母中:

       handleCheck=(id, checked)=>{
           // deep copy old state (check out lodash for a nicer deepCopy)
           const checkedView = JSON.parse(JSON.stringify(this.state.checkedView));
           const checkBox = checkedView.find(view => view.id === id);
           checkBox.isChecked = checked;
           // update whole object of new state
           this.setState(checkedView);
       }
    

    在选择中:

    !警告!您正在更改道具,从不更新道具,这是父母的工作。您也不需要将checkedView置于Selection中的状态,您将其作为prob接收,只需将其传递下来。

    handleCheck = (event, id) => {
        this.props.handleCheck(id, e.target.checked)
    }  
    
    class Selection extends Component {
      constructor(props) {
        super(props)
      }
    
      handleCheck = (event, id) => {
        this.props.handleCheck(id, e.target.checked)
      }  
    
      render() {
        return (
          <div className="">
            <ul className="morefeatures">{
              this.props.checkedView.map((selection) => {
                return (<CheckBox key={selection.id} handleCheck={this.handleCheck} {...selection}  />)
              })
            }
            </ul>
          </div>
        );
      }
    }
    

    在 Checkbox 中,包装 handleCheck 以将事件和 id 都传递给它以识别复选框。

    <input onClick={(e) => props.handleCheck(e, props.id)} type="checkbox" checked={props.isChecked} value={props.value} /> {props.value}
    

    【讨论】:

    • 感谢您的解决方案,但我仍然需要帮助。我用您的代码替换了,但是复选框无法选中/取消选中。所以我把 setState 改成了 this.setState({checkedView: checkedView});但它的状态仍然没有改变,检查仍然从检查中检查
    • 当然!您在控制台中看到任何错误吗?也可以随意尝试 SakoBu 的版本。我试图保持你的整体代码结构不变,但 SakoBu 提出的版本非常干净。您可能想试一试。
    【解决方案2】:

    如果我理解您的问题,我认为这就是您正在寻找的 - 您的架构和逻辑有点偏离,并且您已经将自己编码到了一个角落...- 两个组件(父母和孩子)

    这是你的父级:(保存状态和所有操作它的方法)

    export default class Parent extends React.Component {
        state = {
            checkedView: [
                { id: 1, value: 'A', isChecked: false },
                { id: 2, value: 'B', isChecked: true },
                { id: 3, value: 'C', isChecked: true },
                { id: 4, value: 'D', isChecked: true }
            ]
        };
    
        handleCheck = (id) => {
            this.setState({
                checkedView: this.state.checkedView.map((item) => {
                    if (item.id === id) {
                        return {
                            ...item,
                            isChecked: !item.isChecked
                        };
                    } else {
                        return item;
                    }
                })
            });
        };
    
        render() {
            return (
                <div>
                    {this.state.checkedView.map((item) => (
                        <Child key={item.id} item={item} handleCheck={this.handleCheck} />
                    ))}
                </div>
            );
        }
    }
    

    这是你的孩子:

    从“反应”导入反应;

    export default function Child({ item, handleCheck }) {
        return (
            <div onClick={() => handleCheck(item.id)}>
                {item.value}
                <input type='checkbox' defaultChecked={item.isChecked} />
            </div>
        );
    }
    

    这是一个现场演示:https://stackblitz.com/edit/react-ddqwpb?file=src%2FApp.js

    我猜你可以理解代码在做什么......如果不问......

    【讨论】:

      猜你喜欢
      • 2021-04-30
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      • 2021-01-06
      • 1970-01-01
      • 2013-11-07
      • 2012-02-16
      • 1970-01-01
      相关资源
      最近更新 更多