javascript - 使用 React,是否可以使用 propType 来指定 DOM 元素类型?

标签 javascript reactjs styled-components

我想为排版创建一个 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>;
  }
}

工作示例:https://codesandbox.io/s/xozpn8ol9o

关于javascript - 使用 React,是否可以使用 propType 来指定 DOM 元素类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48964662/

相关文章:

css - 如何使用 Blueprint 3.0 Drawer 作为左侧导航?

forms - 在兄弟组件 Reactjs 中调用函数

javascript - 将 @supports 与样式组件一起使用

reactjs - mui 组件 props,响应式设置

javascript - 无法在 Chrome 中编辑样式?

javascript - 返回函数的值而不是 Array.forEach 中的内部函数

javascript - 对象的属性在 Array.map 中不可用(未定义)

reactjs - 通过 react 增加和减少输入值

javascript - 将字符串数组映射到 React-Native/ES6 中的组件状态

javascript - 如果 Div 位于 img 标签之上,则不会在 Div 上触发 Mousedown 事件 - 问题仅在 IE 中