【问题标题】:React button onClick doesn't fire反应按钮 onClick 不会触发
【发布时间】:2016-09-23 09:44:37
【问题描述】:

我使用create-react-app 命令创建我的项目,我很奇怪onClick 按钮没有触发。我看到了这个我以前从未见过的错误

invariant.js:38 Uncaught Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's "render" method, or you have multiple copies of React loaded

不确定此错误是否会导致按钮单击未触发。 代码非常简单,在其他项目中运行良好。

import React from 'react';

const MyComponent = React.createClass({
    myClick: function () {
      alert("Hello World!");
    },

    render: function() {
      return(
        <div>
          <button onClick={this.myClick}>Click Me</button>
        </div>
      ); 
    }
});

export default MyComponent;

【问题讨论】:

  • 很可能“你加载了多个 React 副本”。你的 package.json 和项目是什么样的?
  • package.json 有这些依赖: "devDependencies": { "react-scripts": "0.4.3" }, "dependencies": { "react": "^15.3.2", " react-dom": "^15.3.2", "react-router": "^2.8.1" },
  • 这个组件安装在哪里以及如何安装?
  • codeReactDOM.render(( ), document.getElementById('root'))
  • 您是否尝试过删除 node_modules 目录并再次使用 npm install ?

标签: reactjs create-react-app


【解决方案1】:

已修复。仅供参考,这是 node_modules 的问题,而不是反应。我在我的项目中使用引导程序,不知何故我忘记了 npm install bootstrap,并且 npm 试图在我的计算机上的根 node_modules 文件夹中找到引导程序,这导致了这个错误。运行“npm install react-bootstrap --save”和“npm install bootstrap@3 --save”后,它就可以工作了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多