【问题标题】:Can you dynamically render pure HTML and a custom component in one React component你能在一个 React 组件中动态渲染纯 HTML 和自定义组件吗
【发布时间】:2021-10-13 15:26:04
【问题描述】:

我想要的是

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

【问题讨论】:

    标签: javascript html reactjs typescript


    【解决方案1】:

    当然,您可以在 React 中制作动态组件。只需将您作为道具的标签传递给组件:

    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>
    
    <div id="root"></div>

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2014-12-18
      • 2018-02-17
      • 2015-02-10
      • 2018-11-26
      • 1970-01-01
      相关资源
      最近更新 更多