使用 React,是否可以使用 propType 来指定 DOM 元素类型?
With React, is it possible to have a propType to specify the DOM element type?
我想创建一个 React UI-Compoment for Typography。可以向组件传递 propType 以指定应呈现哪种元素类型或
可能使用的 propType 如下:as="span"
或 as="p"
这种类型的动态元素类型定义是否可以用 React 实现,或者我是否需要做一些不太优雅的事情并有一个包含两种类型或 return 语句的 Switch 语句?
example: `if (this.props.p) {return <p>....</p>}
使用此建议组件的示例:
<MyC as="span">Hello World</MyC>
<MyC as="p">Hello World</MyC>
您可以这样使用 React.createElement()
:
class MyC extends Component {
state = {
ready: false,
};
componentDidMount() {
this.el = React.createElement(this.props.as, {}, this.props.children);
this.setState({ ready: true });
}
render() {
if (!this.state.ready) {
return null;
}
return this.el;
}
}
用法:
class App extends Component {
render() {
return <MyC as="span">Test</MyC>;
}
}
我想创建一个 React UI-Compoment for Typography。可以向组件传递 propType 以指定应呈现哪种元素类型或
可能使用的 propType 如下:as="span"
或 as="p"
这种类型的动态元素类型定义是否可以用 React 实现,或者我是否需要做一些不太优雅的事情并有一个包含两种类型或 return 语句的 Switch 语句?
example: `if (this.props.p) {return <p>....</p>}
使用此建议组件的示例:
<MyC as="span">Hello World</MyC>
<MyC as="p">Hello World</MyC>
您可以这样使用 React.createElement()
:
class MyC extends Component {
state = {
ready: false,
};
componentDidMount() {
this.el = React.createElement(this.props.as, {}, this.props.children);
this.setState({ ready: true });
}
render() {
if (!this.state.ready) {
return null;
}
return this.el;
}
}
用法:
class App extends Component {
render() {
return <MyC as="span">Test</MyC>;
}
}