{"action":"opened","issue":{"url":"https://api.github.com/repos/riskers/blog/issues/37","repository_url":"https://api.github.com/repos/riskers/blog","labels_url":"https://api.github.com/repos/riskers/blog/issues/37/labels{/name}","comments_url":"https://api.github.com/repos/riskers/blog/issues/37/comments","events_url":"https://api.github.com/repos/riskers/blog/issues/37/events","html_url":"https://github.com/riskers/blog/issues/37","id":330962526,"node_id":"MDU6SXNzdWUzMzA5NjI1MjY=","number":37,"title":"在 React 等 FrameWork 外更新 Model","user":{"login":"riskers","id":5653652,"node_id":"MDQ6VXNlcjU2NTM2NTI=","avatar_url":"https://avatars3.githubusercontent.com/u/5653652?v=4","gravatar_id":"","url":"https://api.github.com/users/riskers","html_url":"https://github.com/riskers","followers_url":"https://api.github.com/users/riskers/followers","following_url":"https://api.github.com/users/riskers/following{/other_user}","gists_url":"https://api.github.com/users/riskers/gists{/gist_id}","starred_url":"https://api.github.com/users/riskers/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/riskers/subscriptions","organizations_url":"https://api.github.com/users/riskers/orgs","repos_url":"https://api.github.com/users/riskers/repos","events_url":"https://api.github.com/users/riskers/events{/privacy}","received_events_url":"https://api.github.com/users/riskers/received_events","type":"User","site_admin":false},"labels":[],"state":"open","locked":false,"assignee":null,"assignees":[],"milestone":null,"comments":0,"created_at":"2018-06-10T11:54:31Z","updated_at":"2018-06-10T11:54:31Z","closed_at":null,"author_association":"OWNER","body":"## 问题\r\n\r\n最近在做浏览器插件的时候，有一个需求是帮助用户填写用户名和密码，以知乎为例:\r\n\r\n![](http://7xlc2a.com1.z0.glb.clouddn.com/15286306526919.jpg)\r\n\r\n一开始以为只需要:\r\n\r\n```\r\nvar username = document.querySelector('input[name=\"username\"]')\r\nusername.value = 'xxx@qq.com'\r\n```\r\n\r\n对于一般的网站来说，这是完全没有问题的，但是知乎是 React 开发的，问题就出现了。虽然从看到的效果来说，的确把用户名填进去了:\r\n\r\n![](http://7xlc2a.com1.z0.glb.clouddn.com/15286311136103.jpg)\r\n\r\n但是，我们可以从看到 `input` 元素的 `value` 值还是之前的 `a`，并没有变化，我们只是改了 View 层，并没有改变 Model 层。\r\n\r\n也可以从 `React devtools` 看到页面上 `input` 的值是和 `Input 组件`的值是不一样的。\r\n\r\n![](http://7xlc2a.com1.z0.glb.clouddn.com/15286312254796.jpg)\r\n\r\n## 原因\r\n\r\n原因很简单，就是因为 React 自己构建了一套数据驱动的系统，我们在外面只能修改 View 层，并不能触发 React 自己的 `updateModel` 方法。\r\n\r\n##　解决办法\r\n\r\n```js\r\nfunction triggerInputChange(node, value) {\r\n  var setValue = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;\r\n  var event = new Event('input', { bubbles: true });\r\n  setValue.call(node, value);\r\n  node.dispatchEvent(event);\r\n}\r\n```\r\n\r\n---\r\n\r\n> [向我捐助](https://github.com/riskers/blog/issues/24) | [关于我](https://github.com/riskers/blog/issues/1) | [工作机会](https://github.com/riskers/blog/issues/31)\r\n"}}
{"actor":{"display_login":"riskers"}}