更改子进程的父状态

时间:2018-03-25 21:42:08

标签: reactjs

我想把我所有的' isSelected'错误期望被点击的一个。 代码:

class Parent extends Component {
    state= {
        menu:[
            {isSelected:true},
            {isSelected:false},
            {isSelected:false}
        ]
    }
    render() {
        let menus=this.state.menu.map((menu,i)=>(
            <MenuElem isSelected={menu.isSelected} />
        ))

        return 
        {menus}      
        );
    }
}

class MenuElem extends Component {
    state = {
        isSelected: this.props.isSelected
    }
    render() {
        const {isSelected} = this.state;
        let clickHandler = ()=>{
            this.setState({ isSelected: true })
            //I want to put all the MenuElem to false : except the clicked one
            // let parent = this._reactInternalInstance._currentElement._owner._instance; ??
            // then foreach MenuElem in my parent I change the isSelected ?
        }
        return (
            <li onClick={clickHandler} className={isSelected ? "is-active" : ""}></li>
        );
    }
}

我不确定我的逻辑是好的。 this._reactInternalInstance._currentElement._owner._instance看起来像是错误的方式。

1 个答案:

答案 0 :(得分:0)

可以对此代码进行各种清理,但在下面我重写了您所拥有的内容并允许孩子更新父级的状态。我相信您有正当理由这样做,而不是在li级别管理li的状态。希望这会有所帮助。

class Parent extends Component {
    state = {
        menu:[
            { isSelected: true },
            { isSelected: false },
            { isSelected: false }
        ]
    }
    render() {
        const { menu } = this.state;
        return (
            { menu.map((menu,i) => {
                return <MenuElem 
                    isSelected={menu.isSelected} 
                    onClick={() => {
                        const newMenu = [...menu];
                        newMenu[i] = !menu[i]
                        this.setState({ menu: newMenu }) }
                    }
                />
            })};
        );
    }
}

class MenuElem extends Component {
    render() {
        const { onClick, isSelected } = this.props;
        return (
            <li onClick={onClick} className={isSelected ? "is-active" : ""}></li>
        );
    }
}

编辑:如果您不需要存储在父级中的状态,您可以轻松地执行此操作:

class Parent extends Component {
    render() {
        return (
            { menu.map((menu,i) => <MenuElem key={i}/> }
        );
    }
}
class MenuElem extends Component {
    state = { isSelected: false }
    render() {
        const { isSelected } = this.state
        return (
            <li onClick={() => {this.setState({ isSelected: !isSelected })}} className={isSelected ? "is-active" : ""}></li>
        );
    }
}