reactjs - 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"
}
}
解决方案
解决方案:
问题源于使用 html-webpack-plugin,它显然在 index.html 中添加了自己的标签。从 index.html 中删除脚本标签解决了我的问题。
推荐阅读
- javascript - 我如何调用 add_to_cart jquery 函数到 php 以获取输入数量值
- netlogo - 如何找出 Y 发生的概率取决于 Netlogo 中的 X1 和 X2?Y , X1 和 X2 是海龟变量
- php - 为什么我不能在此查询中按名称排序?
- java - Java中包命名约定和项目管理的疑惑
- php - 我需要帮助设置新的日志文件
- r - 使用 .pull-left[] 在两列中的 Rmarkdown 不起作用两次
- javascript - 使用路径拆箱属性值
- linux - 显示路径中目录的详细信息 - bash 脚本分配
- elasticsearch - 在运行查询之前初始化 Elasticsearch SearchResponse 对象
- openlayers - 带有 OSM 视网膜图块的 Openlayers:文本太小