gpt4 book ai didi

javascript - 使用 npm 和 browserify 时设置 React 组件初始 Prop

转载 作者:行者123 更新时间:2023-11-30 00:11:12 26 4
gpt4 key购买 nike

我在学习React并关注了Getting Started npmbrowserifybabel 设置指南。我现在可以从我的 main.js 文件生成单个 bundle.js 文件,我可以将其包含在 HTML 页面中以呈现我的 React 组件。到目前为止一切顺利。

我想不通的是如何将初始值从 index.html 文件传递​​到 bundle.js 中定义的组件中。我知道这是一个变量范围问题,因为 ReactDOM 并且组件不是全局的。

让我举个例子。在 bundle.js 中说,我有一个名为 Profile 的 React 组件,它为给定的用户名生成一个小的配置文件小部件。我不想在 main.js/bundle.js 中对用户名值进行硬编码(因为很多示例似乎都这样做)。我希望它是动态的,并且我可以在 HTML 页面中进行更改。因此,在我的 index.html 页面中,我想执行如下操作:

<body>
<div id="profile"></div>
<script src="bundle.js"></script>
<script>
ReactDOM.render(
<Profile user="bob" />,
document.getElementById('profile')
);
</script>
</body>

当然,这行不通,但希望能展示我想要完成的事情。有谁知道做这样的事情的模式?谢谢。

最佳答案

在这种情况下,您需要使用纯 Javascript 来创建元素,而不是 JSX。

<script>
var props = {
user: "bob",
};

// or you can even serialize data structure of your choice
// var props = <?php echo json_encode($profile); ?>;

ReactDOM.render(
React.createElement(Profile, props),
document.getElementById('profile')
);
</script>

由于 Webpack 将捆绑 React/ReactDOM,您将无法在全局范围内访问它。为避免这种情况,请为 Webpack 安装 expose-loaderhttps://www.npmjs.com/package/expose-loader

// index.js may look like this then
require("expose?React!react");
require("expose?ReactDOM!react-dom");
require("expose?Profile!./Profile");
// ./Profile is Profile.js containing component code

关于javascript - 使用 npm 和 browserify 时设置 React 组件初始 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36420452/

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