代码之家  ›  专栏  ›  技术社区  ›  Abdennour TOUMI

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

  •  0
  • Abdennour TOUMI  · 技术社区  · 9 年前
    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组件,我想避免代码冗余,所以我决定删除除最后一个之外的所有渲染方法( render )通过将标记名替换为 this.props.tagName

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

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

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

    1 回复  |  直到 9 年前
        1
  •  2
  •   Pranesh Ravi    9 年前

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