【问题标题】:Append a component dynamically动态附加组件
【发布时间】:2021-03-03 09:00:33
【问题描述】:

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

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```

【问题讨论】:

    标签: reactjs dynamic components


    【解决方案1】:

    尝试为每个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 认为你正在渲染的所有子元素都是一个组件,除非你给它们一个不同的键

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-17
      • 2018-10-14
      • 2018-02-13
      • 2019-12-19
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      相关资源
      最近更新 更多