javascript - 如何根据 prop 动态生成带有标签名称的元素?

标签 javascript html reactjs

我有兴趣构建一个可重复使用的<Element>为了我的特定目的而 react 组件。目的是让任何使用它的人有选择地指定 tagName prop 指示组件将编译成的确切 HTML 元素。就目前情况而言,这就是 Element 的内容。组件看起来像:

import React, { Component } from 'react';    

class Element extends Component {
  constructor(props) {
    super(props);
    this.mapToElement = new Map([
      ['ARTICLE', (props, children) => (<article {...props}>{children}</article>)],
      ['ASIDE', (props, children) => (<aside {...props}>{children}</aside>)],
      ['DIV', (props, children) => (<div {...props}>{children}</div>)],
      ['FOOTER', (props, children) => (<footer {...props}>{children}</footer>)],
      ['HEADER', (props, children) => (<header {...props}>{children}</header>)],
      ['MAIN', (props, children) => (<main {...props}>{children}</main>)],
      ['P', (props, children) => (<p {...props}>{children}</p>)],
      ['SECTION', (props, children) => (<section {...props}>{children}</section>)],
      ['SPAN', (props, children) => (<span {...props}>{children}</span>)]
    ]);
  }

  render() {
    const {
      children,
      tagName = 'DIV',
      ...rest
    } = this.props;

    return (this.mapToElement.get(tagName.toUpperCase())(rest, children));
  }
};

但是,可以看出,该组件成功工作的能力是由 HTML tagName s 的相当详细的映射驱动的。到它们相应的 JSX 语法。我最希望使该组件支持所有非自关闭 HTML 元素,但显然希望这样做而不被迫扩展此映射以包含符合该标准的每个可能的 HTML 元素。

是否有一种更动态、面向 future 的方法来做到这一点?如果有,那会是什么样子?

最佳答案

如果我理解正确的话,您只是为 React.createElement 创建一个包装器这就是所有 JSX 被转译为创建元素的内容:

render() {
  const {
    children,
    tagName = 'div',
    ...rest
  } = this.props;

  return React.createElement(tagName, rest, children);
}

因此:

<Element tagName="span" foo="bar">
  Foobar!
</Element>

将成为(一旦转译):

React.createElement('span', {
  foo: 'bar'
}, 'Foobar!');

这与:

相同
<span foo="bar">Foobar!</span>

如果您只想将其限制为 DOM 元素而不是自定义 React 组件,只需限制 proptype 或自己验证类型即可:

tagName: PropType.string.isRequired

或者甚至是您自己的验证器:

tagName: (props, propName, componentName) => {
  if(typeof props[propName] !== 'string') {
    return new Error(`The ${propName} prop should be a string in ${componentName}`);
  }
}

关于javascript - 如何根据 prop 动态生成带有标签名称的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44867672/

相关文章:

javascript - javascript中鼠标悬停时更改div颜色

html - CSS IE7 背景

javascript - 如何自定义react-calendar以一次只显示一周?

java - 指定默认 a4j :commandButton when press Enter in JSF form

jquery - 在 jquery 中更改多个 div 位置

javascript - Ant Design Form - onAfterChange 处理程序

css - 如何在react类组件中使用react-jss?

asp.net - 使用 Create-React-App,是否可以像使用 grunt/gulp 一样在构建过程中将代码注入(inject)/替换/附加到 index.html 文件中?

javascript - 撤消/重做不能正常工作,缩放后的绘画也不能正常工作

javascript - 更新 html 事件的 Omniture 变量