18910140161

是否可以在一个React组件中动态呈现纯html标记和自定义React.component

顺晟科技

2021-08-10 11:14:02

60

我想要的是

var dynamicTagProps1 = {
    Tag: "span",
    elementAttrs: {
        "aria-label": "test",
        "role": "test"
    }
} as IDynamicTagComponentProps;

var dynamicTagProps2 = {
    Tag: "div",
    elementAttrs: {
        "aria-label": "test2",
        "role": "test2"
    }
} as IDynamicTagComponentProps;

var dynamicTagProps3 = {
    Tag: "MyCustomComp",
    elementAttrs: {
        "aria-label": "test3",
        "role": "test3"
    }
} as IDynamicTagComponentProps;

<body>
    <DynamicTagComponent {...dynamicTagProps1} />
</body>

=>
<body>
    <span aria-label='test' role='test' />
</body>

<body>
    <div aria-label='test2' role='test2' />
</body>

<body>
    <MyCustomComp aria-label='test3' role='test3' />
</body>

我知道可以在React中动态加载纯html元素,类似于:

export interface IDynamicTagComponentProps {
    Tag: string;
    elementAttrs: Record<string, string>;
}

export function DynamicTagComponent(props: IDynamicTagComponentProps) {

    var moreAttr = props.elementAttrs;
    return React.createElement(props.Tag, { ...moreAttr }, null);
}

但是对于React.createElement,对于纯html元素和React组件是不同的。

React.createElement('div')
React.createElement(MyCustomComp)

在一个组件中动态呈现纯html标记和react.component是否可行


顺晟科技:

function Dynamic({ as = 'div', props = {}, children }) { const Tag = as; return <Tag {...props}>{children}</Tag>; } ReactDOM.render( <Dynamic as={'p'} props={{'aria-label': 'test'}}>A dynamic component</Dynamic>, document.getElementById('root') ); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航