2016-10-09 33 views
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(); 
    } 

} 

我已經在上述反應組分,我想避免代碼冗餘,所以,我決定通過更換標記名,以除去所有渲染除了最後一個(render)方法by this.props.tagName反射傳遞標記名字符串道具被渲染

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

但是,它會引發語法錯誤。

如何在react/ES7/Babel中使用標記名的反射?

回答

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/