我们使用Backbone + ReactJS包来构建客户端应用程序.严重依赖臭名昭着的valueLink我们通过自己的包装器将值直接传播到模型,该包装器支持ReactJS接口以进行双向绑定.
现在我们遇到了这个问题:
我们有jquery.mask.js插件以编程方式格式化输入值,因此它不会触发React事件.所有这些都会导致模型从用户输入接收未格式化的值并从插件中忽略格式化的值时导致这种情况.
React似乎有很多依赖于浏览器的事件处理策略.是否有任何常见的方法来触发特定DOM元素的更改事件,以便React会听到它?
我有一个my-checkbox包含复选框,标签,样式等的自定义元素.当切换该复选框时,我CustomEvent在构造函数中定义了一个命名检查,如下所示:
constructor(){
super();
this._shadowRoot = this.attachShadow({mode: 'open'});
this.checkEvent = new CustomEvent("check", {
bubbles: true,
cancelable: false,
});
}
Run Code Online (Sandbox Code Playgroud)
切换复选框时,我会调度该事件:
toggleCheckbox(){
this.dispatchEvent(this.checkEvent);
console.log(this.checkEvent);
...
}
Run Code Online (Sandbox Code Playgroud)
我推断这个事件正在被调度,因为console.log的内容显示了CustomEvent的签名
我有另一个my-checkreport包含my-checkbox的自定义元素,应该对"check"事件作出反应.我在连接的回调函数中定义了一个事件监听器my-checkreport
connectedCallback(){
...
this.addEventListener("check", function (e) {
console.log('listend to check event');
console.log(e);
});
}
Run Code Online (Sandbox Code Playgroud)
但是,这个eventListener永远不会触发,似乎永远不会"听到"在my-checkbox组件中调度的"check"事件.我尝试在构造函数中添加此侦听器并获得相同的结果.
我有什么想法我做错了吗?
背景:我这样做是为了使这些元素可以组合.我还读过,开发Web组件的最佳实践是"使用自定义事件将信息传递出组件......"
一些背景: 我正在尝试在 React 应用程序中使用自定义 Web 组件并尝试侦听来自 Web 组件的事件。我相信您不能只在自定义 Web 组件上以通常的反应方式处理事件。
IE
<custom-button onClick={this.clickHandler}></custom-button>.
Run Code Online (Sandbox Code Playgroud)
我试过这个,但没有用。
问题: 所以,我正在尝试通过addEventListener监听事件,就像在 vanilla js 中所做的那样,但事件处理程序永远不会被调用。
下面是一个例子。我知道<button/>这不是自定义 Web 组件,但它说明了问题:
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.buttonRef = React.createRef();
}
componentDidMount() {
// there are no errors attaching the handler
this.buttonRef.current.addEventListener("onClick", e => {
// this point is never reached
debugger;
console.log("onClick", e);
});
}
render() {
return <button ref={this.buttonRef}>click me</button>;
}
} …Run Code Online (Sandbox Code Playgroud)