Javascript ReactJS,在 React 组件中按类名查找元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42666140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:20:20  来源:igfitidea点击:

ReactJS, find elements by classname in a React Component

javascriptreactjs

提问by wvp

I've a React component. Some elements will be inserted through the children. Some of these elements will have a specific classname. How can I get a list of these DOM nodes in my outermost Component?

我有一个 React 组件。一些元素将通过子元素插入。其中一些元素将具有特定的类名。如何在最外层组件中获取这些 DOM 节点的列表?

<MyComponent>
  <div classname="snap"/>
  <p></p>
  <div classname="snap"/>
  <p></p>
  <div classname="snap"/>
</MyComponent>

What I want to know is how many elements with the classname "snap" are inserted in my component.

我想知道的是在我的组件中插入了多少类名为“snap”的元素。

采纳答案by Alireza

You can use ReactDOM.findDOMNode. Even though the documentation encourage using ref, let's see how it works:

您可以使用ReactDOM.findDOMNode. 尽管文档鼓励使用ref,但让我们看看它是如何工作的:

findDOMNode()

findDOMNode()

ReactDOM.findDOMNode(component)

If this component has been mounted into the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements. In most cases, you can attach a ref to the DOM node and avoid using findDOMNode at all.

When a component renders to null or false, findDOMNode returns null. When a component renders to a string, findDOMNode returns a text DOM node containing that value. As of React 16, a component may return a fragment with multiple children, in which case findDOMNode will return the DOM node corresponding to the first non-empty child.

如果此组件已安装到 DOM 中,则返回相应的原生浏览器 DOM 元素。此方法对于从 DOM 中读取值非常有用,例如表单字段值和执行 DOM 测量。在大多数情况下,您可以将 ref 附加到 DOM 节点并完全避免使用 findDOMNode。

当组件呈现为 null 或 false 时,findDOMNode 返回 null。当组件呈现为字符串时, findDOMNode 返回包含该值的文本 DOM 节点。从 React 16 开始,一个组件可能会返回一个具有多个子节点的片段,在这种情况下, findDOMNode 将返回与第一个非空子节点对应的 DOM 节点。



Note:findDOMNode is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction. findDOMNode only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that has not been mounted yet (like calling findDOMNode() in render() on a component that has yet to be created) an exception will be thrown. findDOMNode cannot be used on functional components.

注意:findDOMNode 是一个用于访问底层 DOM 节点的逃生舱口。在大多数情况下,不鼓励使用此逃生舱口,因为它穿透了组件抽象。findDOMNode 仅适用于已安装的组件(即已放置在 DOM 中的组件)。如果您尝试在尚未安装的组件上调用此方法(例如在尚未创建的组件上调用 render() 中的 findDOMNode()),则会引发异常。findDOMNode 不能用于功能组件。

Also let's look at the ref, which is recommended:

另外让我们看看推荐的ref:

Adding a Ref to a Class Component

向类组件添加 Ref

When the ref attribute is used on a custom component declared as a class, the ref callback receives the mounted instance of the component as its argument. For example, if we wanted to wrap the CustomTextInput above to simulate it being clicked immediately after mounting:

当在声明为类的自定义组件上使用 ref 属性时,ref 回调接收组件的已安装实例作为其参数。例如,如果我们想包装上面的 CustomTextInput 以模拟它在挂载后立即被点击:

class AutoFocusTextInput extends React.Component {
    componentDidMount() {
      this.textInput.focusTextInput();
    }

    render() {
      return (
        <CustomTextInput
          ref={(input) => { this.textInput = input; }} />
      );
    }
}

Note that this only works if CustomTextInput is declared as a class:

请注意,这仅在 CustomTextInput 被声明为类时才有效:

class CustomTextInput extends React.Component {
  // ...
}

回答by Abhishek

You can achieve it, via findDOMNodeof react-dom, like below:

您可以通过findDOMNodeof实现它,react-dom如下所示:

ReactDOM.findDOMNode(<instance-of-outermost-component>).getElementsByClassName('snap') // Returns the elements

If you need the count,

如果你需要计数,

ReactDOM.findDOMNode(<instance-of-outermost-component>).getElementsByClassName('snap').length

回答by Bartek Fryzowicz

Yoy can also use this.props.childrento get number of child nodes with given class:

Yoy 还可以this.props.children用来获取给定类的子节点数:

let snapCount = React.Children.toArray(this.props.children).filter((item) => item.props.className === 'snap').length;