在安装时从React组件获取html类名

rob*_*nnn 2 dom reactjs

也许这违背了反应的理念,但我想知道是否有可能确定刚刚安装的组件的类.

例如:

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>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

lux*_*lux 7

实现此目标的一种方法是向ref您感兴趣的元素添加属性(请参阅render()参考资料),然后我们可以通过this.refsbv 访问该参考,为其提供密钥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>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)