0
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 中使用标记名的反射?

4

1 回答 1

2

您可以将标记名称分配给变量并将该变量用作 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/

于 2016-10-09T07:02:57.337 回答