首页 > 解决方案 > 动态附加组件

问题描述

我尝试动态附加一个组件,这里是我尝试添加到 MainComponent 的 Boards。当循环for运行时,函数 addChild 工作并且列表正在填满,但没有发生任何其他事情,屏幕上没有显示任何内容

const MainComponent = props => (
    <div className={props.className}>
        <p>
            <a href="#" onClick={props.addChild}>Add Another Child Component</a>
        </p>
        {props.boards}
    </div>
);

class MainPage extends React.Component {

    state = {
        numChildren: 0
    }

    onAddChild = () => {
        this.setState({
            numChildren: this.state.numChildren + 1
        });
    }

    render () {

        const boards = [];

        for (var i = 0; i < this.state.numChildren; i += 1) {
            var _id = "board-" + i;
            console.log
            boards.push(<Board id={_id} className="board" />);
        };

        return (
            <div className="test">
                <Title/>
                <MainComponent addChild={this.onAddChild} className="flexbox">
                    {boards}
                </MainComponent>
            </div>
        );
    }
}

export default MainPage```

标签: reactjsdynamiccomponents

解决方案


尝试为每个添加密钥ChildComponent

const boards = [];

for (var i = 0; i < this.state.numChildren; i += 1) {
    var _id = "board-" + i;
    console.log
    boards.push(<Board id={_id} key={_id} className="board" />);
};

因为 react 依赖于渲染在循环内渲染的组件的键

所以 react 认为你渲染的所有子元素都是一个组件,除非你给他们一个不同的键


推荐阅读