Làm thế nào để truy cập vào nút DOM trong một React component?
Làm thế nào để truy cập vào nút DOM trong một React component?
Cách chuẩn là dùng ref: gắn ref vào phần tử JSX, React sẽ gán node DOM thật vào ref.current sau khi commit. ReactDOM.findDOMNode là API cũ, đã deprecated trong StrictMode và bị xoá ở React 19, không nên dùng.
useRefimport { useRef, useEffect } from 'react';
function SearchBox() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus(); // node <input> thật
}, []);
return <input ref={inputRef} placeholder="Tìm kiếm" />;
}
createRefclass SearchBox extends React.Component {
inputRef = React.createRef();
componentDidMount() {
this.inputRef.current.focus();
}
render() {
return <input ref={this.inputRef} />;
}
}
ref là prop bình thường của function component, con chỉ cần chuyển tiếp xuống phần tử DOM.Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.