首页 > 解决方案 > 如果我在组件的父 div 上创建了一个 react ref,是否可以仅在该 ref 中按类名获取元素?

问题描述

我创建了一个新组件,但当然它正在同一页面的许多其他组件中实现。我想知道我是否可以通过与我创建的 ref 相关的类名获取元素?

我已经尝试按类名获取元素,但我得到的元素超出了我试图检索的范围。

import React, { Component } from 'react';

export default class test extends Component {
    constructor(props) {
        super(props);

        this.state = {};
        this.onchange = this.onchange.bind(this);
        this.componentRef = React.createRef();
    }

    onchange = (event) => {
        //This is where I'm not sure if I can get elements by classname in reference to the ref I've created
        let elements = this.componentRef.current;
    };

    render() {
        return <div ref={this.componentRef} />;
    }
}

标签: javascriptreactjsecmascript-6

解决方案


您可以通过在该节点上使用查询选择器来做到这一点。查询选择器全部

import React, { Component } from 'react';

export default class test extends Component {
    constructor(props) {
        super(props);

        this.state = {};
        this.onchange = this.onchange.bind(this);
        this.componentRef = React.createRef();
    }

    onchange = (event) => {
        // you can access the children components directly here
        let elements = this.componentRef.querySelectorAll('.child');
    };

    render() {
        return <div ref={this.componentRef} />;
    }
}

推荐阅读