也许这违背了反应的哲学,但我想知道是否有可能确定刚刚安装的组件的类。
例如:
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>
)
}
}
实现这一目标的一种方法是向您感兴趣的元素添加一个 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>
);
}
}