Javascript 如何基于道具动态生成具有标记名的元素?
我感兴趣的是为我的特定目的构建一个可重用的Javascript 如何基于道具动态生成具有标记名的元素?,javascript,html,reactjs,react-jsx,Javascript,Html,Reactjs,React Jsx,我感兴趣的是为我的特定目的构建一个可重用的React组件。其目的是让任何使用它的人都可以选择指定一个标记名道具,该道具指示组件将编译到的确切HTML元素。目前,以下是元素组件的外观: import React, { Component } from 'react'; class Element extends Component { constructor(props) { super(props); this.mapToElement = new Map([
React组件。其目的是让任何使用它的人都可以选择指定一个标记名
道具,该道具指示组件将编译到的确切HTML元素。目前,以下是元素
组件的外观:
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));
}
};
import React,{Component}来自'React';
类元素扩展组件{
建造师(道具){
超级(道具);
this.mapToElement=新映射([
['ARTICLE',(props,children)=>(对应于它们相应的JSX语法。我最想让这个组件支持所有非自动关闭的HTML元素,但显然希望这样做,而不必强制扩展这个映射,以包括符合该标准的所有可能的HTML元素
是否有一种更具动态性、更能证明未来的方法来实现这一点,如果是的话,那会是什么样子?如果我理解正确,您只是在创建一个包装器,而所有JSX都是为它传输来创建元素的:
render() {
const {
children,
tagName = 'div',
...rest
} = this.props;
return React.createElement(tagName, rest, children);
}
因此:
这与:
<span foo="bar">Foobar!</span>
甚至您自己的验证器:
tagName: (props, propName, componentName) => {
if(typeof props[propName] !== 'string') {
return new Error(`The ${propName} prop should be a string in ${componentName}`);
}
}
Jeeeez…我觉得自己很笨。我已经习惯了ES6风格的React代码,我已经完全忘记了createElement
方法对我们仍然可用。你完全了解我所寻找的。谢谢@AndrewLi@IsenrichO没问题,这发生在我们中最好的人身上。干杯!我更倾向于在应用程序中使用自定义验证器这种情况。这似乎是对自动关闭HTML标记发出警告的最佳场所。尽管我仍然没有看到一种更有效的方式来进行这种验证工作,而不是基于检查那些被禁止的标记列表。类似于,if(['BR','HR','IMAGE','INPUT','META','SOURCE','TRACK','WBR'])。包括(propName.toUpperCase()){//throw error}
@IsenrichO好吧,我不知道有什么方法可以获得自动关闭标签列表,所以遗憾的是,这将是唯一的方法。
<span foo="bar">Foobar!</span>
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}`);
}
}