How to Get DOM Elements in React?
In React, accessing DOM elements is not as straightforward as using getElementById() in traditional JavaScript. React handles DOM manipulation differently, prioritizing performance and virtual DOM diffing.
React Refs
To access DOM elements in React, you need to use refs. Refs are a way for React to maintain a reference to a DOM element created by a React component. There are multiple ways to create refs in React:
Callback Refs:
A recommended approach is to use callback refs. With callback refs, you pass a callback function as the value of the ref attribute. The function receives the DOM element as its argument.
Example:
<Progressbar completed={25}>
React.createRef (Functional Components):
For functional components introduced in React 16.8, you can use React.createRef(). This returns a ref object that you can assign to an attribute.
Example:
const myRef = React.createRef(); const handleClick = () => { const node = myRef.current; } return <div ref={myRef} onClick={handleClick} />;
Accessing the Element
Once you have created a ref, you can access the DOM element as follows:
For example:
const node = this.refs.Progress1; const node = this.Progress[0]; const node = myRef.current;
In your specific case, you can use callback refs to access the progress bar elements and perform the handleClick10 function:
handleClick10 = (e) => { const progressElement = this.refs[this.state.baction]; if (progressElement) { progressElement.addPrecent(10); } };
The above is the detailed content of How Can I Access DOM Elements in React?. For more information, please follow other related articles on the PHP Chinese website!