您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

解析ReactJs中箭头函数的使用

2025/8/21 13:19:09发布7次查看
这篇文章主要介绍了浅谈箭头函数写法在reactjs中的使用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
es7中的箭头函数写法真的是很方便,而现今reactjs又非常流行而且好用,非常适合有java面向对象经验的同学学习和使用,在使用reacjs构建组件时,如果想要使用箭头函数写法定义函数该怎么办呢?
首先,如果你直接在react组件中使用箭头函数写法定义函数,编译是不会通过的,会报出语法错误。
error in ./modules/repos.js module build failed: syntaxerror: e:/allworkspace/react-router/trunk/lessons/01- setting-up/modules/repos.js: unexpected token (4:16) 2 | import {link} from 'react-router'; 3 | export default class repos extends component{ > 4 | handlesubmit = () => { | ^ 5 | 6 | } 7 | render(){ @ ./index.js 19:13-39
如上所述,handlesubmit函数定义失败,那要怎样才能让你的reactjs项目支持箭头函数写法呢,答案是 babel-preset-es2015,babel-preset-react,babel-preset-stage-0,babel-plugin-transform-class-properties. 只有添加这四个组件,这样才能支持箭头函数写法。
那么我们该怎么做呢,首先当然是安装和下载babel-preset-es2015,babel-preset-react,babel-preset-stage-0,babel-plugin-transform-class-properties 这四个组件了。
npm install --save-dev babel-preset-es2015 npm install --save-dev babel-preset-react npm install --save-dev babel-preset-stage-0 npm install --save-dev babel-plugin-transform-class-properties
然后,在根目录下添加.babelrc 文件,文件内容是
{ presets: [ "react","es2015","stage-0"], "plugins": ["transform-class-properties"] }
在然后,在webpack.config.js中添加配置。
module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=react,presets[]=es2015,presets[]=stage-0' } ] }
其中,这句 loader: 'babel-loader?presets[]=react,presets[]=es2015,presets[]=stage-0' 需要留意,而且顺序必须这样,不能错,要不然会报错。
error in ./modules/repos.js module build failed: syntaxerror: e:/allworkspace/react-router/trunk/lessons/01- setting-up/modules/repos.js: missing class properties transform. 2 | import {link} from 'react-router'; 3 | export default class repos extends component{ > 4 | handlesubmit = () => { | ^ 5 | 6 | } 7 | render(){ @ ./index.js 19:13-39
好了,这样就可以为所欲为,随心所欲的使用自己喜爱的箭头函数写法了。
以上就是解析reactjs中箭头函数的使用的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product