+-
react js中document.querySelector的替代方案

我看过很多关于使用 useRef 在react js中。根据 react js文档, Refs provide a way to access DOM nodes or React elements created in the render method.. 从所有的文档中,我了解到,如果你想访问一个dom元素,你必须添加这样的ref。 <div ref={myRef}然后就可以轻松访问它了。我的理解是,如果你想访问一个dom元素,你必须添加这样的ref: ,之后就可以很容易地访问它。useRef 当我们可以访问html标记时使用。

疑问: 如何访问css选择器 (.class, #id),当我的html是由一个库生成的,比如AntD或者其他的库?如果我不能使用这个选择器,如何访问这个选择器?document.querySelector 根据反应文档?EX:

 document.querySelector('my selector').style.color = 'yellow';
在react js中,最后一个代码片断的替代方案是什么?

注意: 我不想用css改变样式,但我需要根据一些js逻辑来改变。

1
投票

可以 使用 querySelectorquerySelectorAll 在你要访问的DOM结构是在React之外生成的情况下。当你没有其他选择的时候,这绝对没有问题。

你可能会在你的组件的最外层元素上使用它们,或者在你让非React的lirbray做它的事情的元素上使用它们(你会通过ref获得),而不是在 document因此,他们只是在你的组件的DOM部分而不是整个文档中工作。

"use strict";
const { useState, useEffect, useRef } = React;

// A stand-in for your non-React library
function nonReactLibraryFunction(element, value) {
    element.innerHTML =
        `<div>
            This is content from the non-React lib, value =
            <span class="value">${value}</span>
        </div>`;
}

// A stand-in for your component
const Example = ({value}) => {
    // The ref for the wrapper around the lib's stuff
    const fooRef = useRef(null);

    // When `value` changes, have the library do something (this
    // is just an example)
    useEffect(() => {
        // Valid target?
        if (fooRef.current) {
            // Yes, let the lib do its thing
            nonReactLibraryFunction(fooRef.current, value);

            // Find the element we want to change and change it
            const color = value % 2 === 0 ? "blue" : "red";
            fooRef.current.querySelector(".value").style.color = color;
        }
    }, [value]);

    return (
        <div>
            This is my component, value = {value}.
            <div ref={fooRef} />
        </div>
    );
};

// A wrapper app that just counts upward
const App = () => {
    const [value, setValue] = useState(0);

    useEffect(() => {
        setTimeout(() => setValue(v => v + 1), 800);
    }, [value]);

    return <Example value={value} />;
};

ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.development.js"></script>
0
投票

如果你使用外部的库来生成他们自己的标记. 没有什么不好的,使用 element.querySelector

你可以做这样的事情。

React.useEffect(() => {
   const element = document.querySelector(selector);
}, []);

但如果你使用的是React生态系统中的一个库 比如Antd或者material -ui 他们可能有一个带有refs的API。它可以像这样调用 innerRef, nestedRef 或者只是 ref

0
投票

除了前面的回答:如果这个生成的html是在你的组件里面生成的,你可以在你的组件上使用querySelector。useRef.current 来搜索组件内的元素;)

const Component = () => {
  const componentRef = useRef(null);

  useEffect(() => {
    const elFromLibraryComponent = componentRef.current.querySelector('my selector');

    if (elFromLibraryComponent) {
       ...do something...
    }
  }, [])

  return (
    <div ref={componentRef}>
      <ComponentFromLibrary />
    </div>
  )
}

甚至有一些库允许将 ref 作为道具传递给组件,所以它也很有用。

-1
投票

我们还可以借助document.getElementsByTag('TagName').Document.getElementById('IdName'),Document.getElementsByClass('ClassName')来操作HTML Dom元素的标签、id、类。