是否可以获取虚拟 DOM 上事件目标的父节点?
在我的基本 React 组件中,我有一个由 onClick 事件触发的方法,我想获取父虚拟 DOM 节点属性。
handleClick(e){
// The following code only gives me the actual DOM parent Node
ReactDOM.findDOMNode(e.target).parentNode
}
最佳答案
是的。 React 在虚拟 DOM 模型上工作,并且仅在需要时才会更新真实的浏览器 DOM。 React 中的事件也在虚拟 DOM 上工作,它们被称为 synthetic事件。如果您发现出于某种原因需要底层浏览器级事件,只需使用nativeEvent属性即可获取 it .
React Virtual DOM 中有一些限制,您可以从 here 中了解到。 :
此外,this可能会有所帮助,并解释了虚拟 DOM 和浏览器 DOM 之间的区别。
<小时/>浏览器 DOM 只是页面元素的抽象,而 React DOM 将是该抽象的抽象。
render
方法ReactDOM
至关重要的是我们如何将 React 元素发送到浏览器 DOM:
var React = require('react');
var ReactDOM = require('react-dom');
var root = React.createElement('div');
ReactDOM.render(root, document.getElementById('example'));
^
|---- Where React elements from React Virtual DOM enter the Browser DOM
在 React 中,我们处理的是 React Elements 和 React Components。
由于 React Element 是 DOM 元素的虚拟表示,因此要处理事件并捕获父元素,您需要通过以下三种方式之一创建 React 组件:
例如,要在点击事件中导航父级,您可以检查以下内容:
var parent = this._reactInternalInstance._currentElement._owner._instance;
引用号:is there any way to access the parent component instance in React?和 http://jsfiddle.net/BinaryMuse/j8uaq85e/
关于reactjs - react 事件目标父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41934055/