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?
ReactDOM
cung cấp cho bạn phương thức ReactDOM.findDOMNode(param)
để tìm đối tượng Node tương ứng với tham số của phương thức.
Bên trong Class Component nếu bạn gọi phương thức ReactDOM.findDOMNode(this)
, nó sẽ trả về cho bạn nút gốc (Root Node) của mô hình DOM. Ví dụ:
// File: findDOMNode-example.jsx
class Fruits extends React.Component {
doFind() {
// Find root Node of this Component
var node = ReactDOM.findDOMNode(this);
node.style.border = "1px solid red";
}
render() {
return (
<ul>
<li>Apple</li>
<li>Apricot</li>
<li>Banana</li>
<li>
<button onClick={() => this.doFind()}>Find Root Node</button>
</li>
</ul>
);
}
}
// Render
ReactDOM.render(<Fruits />, document.getElementById("fruits1"));
<!DOCTYPE html>
<ht...
senior
Chưa có bình luận nào