【发布时间】:2017-07-16 13:03:10
【问题描述】:
我想做的非常简单的事情:我正在构建一个 React 应用程序,使用 webpack 来捆绑它。我有一些属性想要通过配置 JSON 文件传递,并且能够在我的 React 代码中引用这些值。
我想出了一种方法来做到这一点,但似乎应该有一种更直接的方法来做到这一点。寻找有关如何更干净地执行此操作的建议。
这是我正在做的简化版本,它有效。
我的想法是我将此值线程化到 HTML 的隐藏元素中,然后将其作为道具传递到我的主要 React 元素中。我更喜欢将这个值直接传递给 React props 的方法,但我还没有找到一种方法来做到这一点。
properties.json
{
"myKey": "foo (possibly dynamically generated by a build step)"
}
webpack.config.js
const config = require(__dirname + '/properties.json');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body',
metadata: config
});
// ... Rest of normal-looking webpack with babel-loader and react preset
index.html
<html>
<head><!-- normal head contents --></head>
<body>
<!-- One of these per key-value pair in my properties -->
<div id="config-myKey" style="display: none">
<%= htmlWebpackPlugin.options.metadata.myKey %>
</div>
<div id="app"></div>
</body>
</html>
反应应用(index.js):
const Main = React.createClass({
render: function() {
return(<p>This is the value for myKey: ${this.props.myKey}</p>);
}
});
// Read in the value from the hidden HTML element, and pass it through to the
// React app as props. This part feels like there should be a better way to
// do it.
const myValue = document.getElementById('config-myKey').innerHTML.trim();
ReactDOM.render(
<Main myKey=${myValue}/>,
document.getElementById('app')
);
【问题讨论】:
-
如果您在模块中声明了一些值,为什么不直接导入它们呢? (我错过了什么吗?)
-
我希望这些值由(之前的)构建步骤生成。如中所示,properties.json 将即时填充,而不是硬编码。
-
谢谢@azium!这正是我所需要的。