2016-03-01 62 views
1

也許這是違反反應的哲學,但我想知道是否有可能確定剛剛安裝的組件的類。安裝時從React組件獲取html類名稱

例如:要實現這一目標

export class HelloWorldDiv extends Component { 
    componentDidMount() { 
     // can I magically determine that the class of the component that just mounted (in this case 'hello-world')? 
     // totally open to using jquery if necessary 
    } 

    render() { 
     return (
      <div className="hello-world"> 
      </div> 
     ) 
    } 
} 

回答

5

一種方式是一個ref屬性添加到您感興趣的(見render())的元素,然後我們就可以通過this.refs BV訪問提供參考它的關鍵,myDiv。然後使用普通JS我們可以獲得class屬性:

class HelloWorldDiv extends React.Component { 

    componentDidMount() { 
     console.log(this.refs.myDiv.getAttribute('class')); 
    } 

    render() { 
     console.log('Class: ', this.constructor.name); 
     return (
      <div ref="myDiv" className="hello-world"> 
      </div> 
     ); 
    } 
}