javascript - 如果我在组件的父 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} />;
}
}
解决方案
您可以通过在该节点上使用查询选择器来做到这一点。查询选择器全部
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} />;
}
}
推荐阅读
- python - Python 键盘模块
- c++ - lamda 中的不同类型,在捕获列表中引用
- flutter - 如何在 TargetPlatform.android 上实现侧滑关闭页面?
- c++ - 如何将 getline 与标准输入一起使用?
- eos - 如何逐字节确定我的 EOS RAM?
- powershell - 如何在 Microsoft.Xrm.Data.Powershell 中查看属性值?
- scala - 在哪里可以找到cats.NonEmptyParallel[IO,F]?
- python - 替换字符串中不需要的特殊字符,保留两个数字之间的特殊字符
- python - 我怎样才能让这个 python 程序记住以前的值并添加它?
- ios - 应用程序支持与 GKSavedGame