反射将 tagName 作为要呈现的字符串道具传递

reflection to pass tagName as string props to be rendered

class Button  extends React.Component{
    renderAnchor(){
      return <a onClick={this.props.onClick}>{this.props.children}</a>
    }
    renderButton(){
       return <button onClick={this.props.onClick}>{this.props.children}</button> 
    }
    render(){
         return (this.tagName==='a')?this.renderAnchor():this.renderButton();
    }

}

我有上面的 react-component ,我想避免代码冗余,所以,我决定删除除最后一个 (render) 之外的所有渲染方法,方法是将标记名替换为 this.props.tagName

     render(){
         return <{this.props.tagName} onClick={this.props.onClick}>{this.props.children}</{this.props.tagName}>
    }

但是,它会引发语法错误。

如何在 react / ES7/ Babel 中使用标签名的反射?

您可以将标签名称分配给变量并将该变量用作 HTML 标签。

例如:

render(){
    const CustomTag = this.props.tagName //assign it to the variable

    return <CustomTag
      onClick={this.props.onClick}>
          {this.props.children}
      </CustomTag>

演示:https://jsfiddle.net/88honb0z/