我只是按照这里的优秀指南来设置一个非常简单的 React + Webpack 4 + Babel 7 - https://www.robinwieruch.de/minimal-react-webpack-babel-setup/
我在本地主机上运行了一些东西,并创建了我的第一个自定义“hello world”样式 jsx 组件,这很棒!
然后我尝试创建一个非常简单的 clickHandler
import React, { Component } from 'react';
export default class testComponent extends Component {
ClickHandler = () => {
console.log("I was called")
};
render() {
return (
<div>
Test component test
<button onClick={this.ClickHandler}>Click me</button>
</div>
)
}
}
现在这会导致我的本地主机出现空白页面,但我认为我的代码是正确的?
我的猜测是我对 ES6 箭头函数的使用,尽管我认为 babel 做了它并在需要时转换了它......所以我也尝试过 ES5 语法,但仍然出现空白屏幕
感觉就像我错过了对这里实际发生的事情的一些理解 - 我想不出我会从哪里开始调试
您可能还没有设置 babel 来处理类属性。
您可以安装以下 babel 插件:https :
//www.npmjs.com/package/@babel/plugin-proposal-class-properties
npm install --save-dev @babel/plugin-proposal-class-properties
...然后更新您的.babelrc文件以使用该插件:
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-proposal-class-properties"
]
}
或者,您可以更改代码以删除类属性的使用:
import React, { Component } from 'react'
export default class testComponent extends Component {
clickHandler() {
console.log("I was called")
}
render() {
return (
<div>
Test component test
<button onClick={this.clickHandler}>Click me</button>
</div>
)
}
}
我希望这有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句