首页 > 解决方案 > onClick 事件未在 React.js 中触发

问题描述

我有一个非常恼人的问题。我以前从未有过这个。

此组件和其他组件中的 onClick 也根本不起作用。在 devTools 中,我可以看到它event附加到特定的 DOM 元素,但单击它不会启动任何操作。我在控制台中看不到我的输出。我在这种情况下使用 webpack,我担心它可能配置错误,所以我还附加了 webpack.config.js 和 package.json 文件。

  import React from "react";
    
    const Controls = () => {
      const playMusic = () => {
        console.log("play");
      };
    
      const prevSong = () => {};
    
      const nextSong = () => {
        console.log("next");
      };
    
      return (
        <div className="player-controls">
          <i className="fas fa-backward" onClick={prevSong} id="prev" title="Previous"></i>
          <i className="fas fa-play-circle main-button" onClick={playMusic} id="play" title="Play"></i>
          <i className="fas fa-forward" id="next" onClick={nextSong} title="Previous"></i>
        </div>
      );
    };
    
    export default Controls;

webpack.config.js

  const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

config = {
  entry: "./App/App.js",
  devServer: {
    hot: true,
    port: 3000,
    contentBase: path.join(__dirname, "App")
  },

  output: {
    filename: "bundled.js",
    path: path.resolve(__dirname, "App")
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "App", "index.html")
    })
  ],

  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"]
      },
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-react", ["@babel/preset-env", { targets: { node: "12" } }]]
          }
        }
      },

      {
        test: /\.mp3$/,
        loader: "file-loader"
      }
    ]
  },

  mode: "development"
};

module.exports = config;

和 package.json

{
  "name": "music-player-react",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack serve",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/core": "^7.14.0",
    "@babel/preset-env": "^7.14.1",
    "@babel/preset-react": "^7.13.13",
    "babel-loader": "^8.2.2",
    "css-loader": "^5.2.4",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^5.3.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "style-loader": "^2.0.0",
    "webpack": "^5.36.2",
    "webpack-cli": "^4.7.0",
    "webpack-dev-server": "^3.11.2"
  }
}

标签: reactjs

解决方案


解决方案:

问题源于使用 html-webpack-plugin,它显然在 index.html 中添加了自己的标签。从 index.html 中删除脚本标签解决了我的问题。


推荐阅读