我想为排版创建一个 React UI-Compoment。可以向组件传递 propType 来指定应呈现哪种元素类型或
也许 propType 的用法如下:as="span"
或 as="p"
这种类型的动态元素类型定义可以用 React 实现吗?还是我需要做一些不太优雅的事情,并使用具有两种类型的 Switch 语句或 return 语句?
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>;
}
}
关于javascript - 使用 React,是否可以使用 propType 来指定 DOM 元素类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48964662/