我刚接触使用带有React的ES6类,之前我已经将我的方法绑定到当前对象(在第一个示例中显示),但ES6是否允许我使用箭头将类函数永久绑定到类实例?(当作为回调函数传递时很有用.)当我尝试使用它时,我遇到错误,就像使用CoffeeScript一样:
class SomeClass extends React.Component {
// Instead of this
constructor(){
this.handleInputChange = this.handleInputChange.bind(this)
}
// Can I somehow do this? Am i just getting the syntax wrong?
handleInputChange (val) => {
console.log('selectionMade: ', val);
}
Run Code Online (Sandbox Code Playgroud)
因此,如果我要传递SomeClass.handleInputChange
给setTimeout
它,那么它将被限定为类实例,而不是window
对象.
我已经开始了一个项目,我在后端使用React JS作为后端的节点js.我用webpack捆绑了JS文件.我使用了babel和其他必要的东西.当我在react类中使用箭头函数时,它会产生语法错误.像模块构建失败:SyntaxError:意外的令牌.但我可以在节点中使用箭头功能,没有任何问题.
这是我的webpack配置文件
import path from 'path';
import webpack from 'webpack';
import 'react-hot-loader/patch';
export default{
devtool: 'eval',
entry:[
'react-hot-loader/patch',
'webpack-hot-middleware/client?reload=true',
path.join(__dirname,'client/index.js')],
output:{
path:'/',
publicPath:'/'
},
plugins:[
new webpack.NoErrorsPlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin()
],
module:{
loaders:[
{
test:/\.js$/,
include:path.join(__dirname,'client'),
loaders: ['react-hot-loader/webpack', 'babel']
},
{
test: /\.jpe?g$|\.gif$|\.svg$|\.png$/i,
loader: 'file-loader?name=[name].[ext]'
}
]
},
resolve:{
extension:['','.js']
}
}
Run Code Online (Sandbox Code Playgroud)
我的React文件
class mapSidebar extends React.Component{
constructor(props,context){
super(props,context);
this.state = {
dataSource: []
};
this.handleUpdateInput = this.handleUpdateInput.bind (this);
}
handleUpdateInput = (value) => {
this.setState({ …
Run Code Online (Sandbox Code Playgroud) 我已经用webpack-middleware建立了反应全栈环境.我的代码中有一些es6语法但是在没有构造函数或命名箭头函数的情况下我得到错误.例如,我想使用semantic-ui作为反应排序表:https: //react.semantic-ui.com/collections/table#table-example-sortable 在编译时我收到此错误: 在此处输入图像描述
我认为这是因为我在下面附加了错误的webpack设置.
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './client/index.js',
output: {
path: '/',
filename: 'bundle.js'
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'client/index.html'
})
]
};
Run Code Online (Sandbox Code Playgroud)
.babelrc
{
"presets": ["env", "react", "es2015"]
}
Run Code Online (Sandbox Code Playgroud)