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