gpt4 book ai didi

javascript - 将 getChildContext() 传递给 ReactJS 高阶组件会在 Webpack 中引发意外的 token 错误

转载 作者:行者123 更新时间:2023-12-03 06:15:46 26 4
gpt4 key购买 nike

我从 HERE 得到了以下示例制作一个高阶组件来可靠地传递上下文。

但是,使用 webpack 编译脚本时,在传递 getChildContext() 函数时出现 Unexpected token 错误:

getChildContext = () => getChildContext(this.props);
^^^

代码:

const provideContext = 
(childContextTypes, getChildContext) => (Component) => {
class ContextProvider extends React.Component {
getChildContext = () => getChildContext(this.props);

render() {
return <Component {...this.props} />;
}
}
ContextProvide.childContextTypes = childContextTypes;

return ContextProvider;
};

有传递函数的解决方法吗?

我的 webpack 配置:

var common = {
output: {path: BUILD_DIR},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
include: APP_DIR,
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
},
{
test: /\.(png|jpg)$/,
loader: 'file-loader'
}
]
},
resolve: {
alias: {
'react': path.join(__dirname, 'node_modules', 'react'),
'react-dom': path.join(__dirname, 'node_modules', 'react-dom')
},
extensions: ['', '.js']
},

};


config.push(
merge(common, {
entry: {
ItemPage:APP_DIR+'/page/'+fileName+'.js',

},
devtool: 'source-map',
output: {
filename: "[name].js",
libraryTarget: 'umd',
library: "[name]"
},
externals: [{
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react',

},
"react-dom": "ReactDOM"
}]

})
);

module.exports = config;

最佳答案

您收到意外的 token ,因为您缺少一个 babel 插件 transform-class-properties包含在 stage-1 预设

With stage-1 ,它有效

Without stage-1 ,它不起作用

所以为了解决这个问题,你必须

1°安装stage-1

npm install --save-dev babel-preset-stage-1

2° 将其添加到 .babelrc

{
"presets": ["react","es2015","stage-1"]
}

或者到 webpack 配置

query: {
presets: ["react","es2015","stage-1"]
}

关于javascript - 将 getChildContext() 传递给 ReactJS 高阶组件会在 Webpack 中引发意外的 token 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39113617/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com