动态名称反应组件未创建

时间:2018-08-17 13:20:37

标签: reactjs

我已经阅读了主题和教程,但是我不知道我的动态名称有什么问题:

我尝试了3种不同的方式。只有第一个在工作。

我在.js文件中:

render() {
    let componentList = {
        Delete: 'DeleteIcon',
    };
    let ComponentName = "Delete";
    let ChildComponent = componentList[ComponentName];


    let test = (CompName, props) => {
        return React.createElement(CompName, props);
    };

    return (
        <div>
            <DeleteIcon color="#71f1aa" />
            <ChildComponent color="#71f1aa" />
            {test('DeleteIcon', {color: "#71f1aa"})}
        </div>
    );
}

<DeleteIcon color="#71f1aa" />是我的组件之一,显示效果很好,

<ChildComponent color="#71f1aa" />将被创建,但将为空

{test(ChildComponent, {color: "#71f1aa"})}将被创建,但也将为空。

在第二种和第三种情况下,它将在props上处于只读状态,并且不会显示我的组件。

这是我的DeleteIcon:

import React, { Component } from 'react';

type DeleteIconProps = {
    className?: ?string,
    color?: string
};

export default class DeleteIcon extends Component<DeleteIconProps> {
    static defaultProps = {
        color: "#40B474"
    };

    render() {
        const {color, className} = this.props;
        return (
            <svg viewBox="0 0 59 59" className={className} height={24} width={24}>
                <defs>
                    <clipPath id="a">
                        <path d="M0 0h59v59H0z"/>
                    </clipPath>
                </defs>
                <g clip-path="url(#a)">
                    <path d="M52.5 6H38.456c-.11-1.25-.495-3.358-1.813-4.711C35.809.434 34.751 0 33.499 0H23.5c-1.252 0-2.31.434-3.144 1.289C19.038 2.642 18.653 4.75 18.543 6H6.5a1 1 0 1 0 0 2h2.041l1.915 46.021C10.493 55.743 11.565 59 15.364 59h28.272c3.799 0 4.871-3.257 4.907-4.958L50.459 8H52.5a1 1 0 1 0 0-2zm-32 44a1 1 0 1 1-2 0V17a1 1 0 1 1 2 0v33zm10 0a1 1 0 1 1-2 0V17a1 1 0 1 1 2 0v33zm10 0a1 1 0 1 1-2 0V17a1 1 0 1 1 2 0v33zM21.792 2.681C22.24 2.223 22.799 2 23.5 2h9.999c.701 0 1.26.223 1.708.681.805.823 1.128 2.271 1.24 3.319H20.553c.112-1.048.435-2.496 1.239-3.319z" fill={color}/>
                </g>
            </svg>
        )
    }
}

我该怎么办? 泰语为您提供帮助!

1 个答案:

答案 0 :(得分:0)

问题出在componentList

let componentList = {
    Delete: 'DeleteIcon',
};

componentList.Delete是字符串,而不是组件。 将componentList更改为

let componentList = {
    Delete: DeleteIcon
};

解决了这个问题。

相关问题