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

问题描述

我在父组件中,我正在尝试通过单击按钮动态添加新组件。我将只粘贴必要的代码,因为我的文件很大。

所以在它下面我们说父组件:

    export default class Parent extends Component {
    constructor(props) {
        super(props);

        this.state = {
            conditions: [{attribute: '', operator: '', value: ''}]
        }
    }

    addCondition = (e) => {
        this.setState((prevState) => ({
            conditions: [...prevState.conditions, { attribute: '', operator: '',value: '' }],
        }));
    }

    render() {
        let {conditions} = this.state
        return(
                <Row>
                    <TextButton label='Add Child' onClick={(e) => {this.addCondition}} flat={true} />
                </Row>
                <Row>
                    <ChildElement conditions={conditions} />
                </Row>
            )
    }

}

这是我要动态渲染的 ChildElement:

export class ChildElement extends Component {
    constructor(props) {
        super(props);

        this.state = {
            attribute: '',
            operator: '',
            action: '',
        };
    }

    render() {
        return (
            this.props.conditions.map((val, idx)=> {
                let attributeId = `attributeId-${idx}`,
                    operatorId = `operatorId-${idx}`,
                    valueId = `valueId-${idx}`
                return (
                    <Row>
                        <Col >
                            <Dropdown id={attributeId}  />
                        </Col>
                        <Col >
                            <Dropdown id={operatorId}  />
                        </Col>
                        <Col>
                            <Dropdown id={valueId} />
                        </Col>
                    </Row>
                );
            })
        );
    }
}

加载父组件时出现错误:

Uncaught Error: ConditionElement.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

标签: reactjsredux

解决方案


我会在这里得到一个疯狂的猜测,因为我没有看到整个代码。
您正在导入,ChildElement就好像它是一个default export但实际上它是一个命名的导出。

export class ChildElement

应该这样导入:

import {ChildElement} from './path'

并不是:

import ChildElement from './path'

推荐阅读