我正在制作并监听普通的 DOM CustomEvent
来与父节点进行通信:
在 child 中:
var moveEvent = new CustomEvent('the-graph-group-move', {
detail: {
nodes: this.props.nodes,
x: deltaX,
y: deltaY
},
bubbles: true
});
this.getDOMNode().dispatchEvent(moveEvent);
在父级中:
componentDidMount: function () {
this.getDOMNode().addEventListener("the-graph-group-move", this.moveGroup);
},
这可行,但是有没有一种特定于 React 的方法会更好?
最佳答案
如上所述:
The React way would be to pass callbacks down to children explicitly via props — . There's no support for custom events w/ bubbling in React.
响应式(Reactive)编程抽象是正交的:
Programming interactive systems by means of the observer pattern is hard and error-prone yet is still the implementation standard in many production environments. We present an approach to gradually deprecate observers in favor of reactive programming abstractions. Several library layers help programmers to smoothly migrate existing code from callbacks to a more declarative programming model.
React 哲学基于命令模式:
引用文献
关于reactjs - 用于与父节点通信的react.js自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21951734/