Вы можете использовать querySelector
и querySelectorAll
в ситуациях, когда структура DOM, к которой вы обращаетесь, генерируется вне React. Это абсолютно нормально, когда у вас нет другого выбора.
Вы, вероятно, использовали бы их на самом внешнем элементе вашего компонента или на элементе, в котором у вас есть lirbray не-React, который делает свое дело (что вы ' d получить через ссылку), а не на 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>