reactjs - 如何将 html div 中的 props 传递给 react 中的函数组件?
问题描述
不知道如何将属性从 html 传递到反应文件。这是现有的代码,
<html>
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
<body>
<div id="mydiv" parm="some info"></div>
<script type="text/babel" src="h2.js"></script>
</body>
</html>
反应文件,我现在手动发送道具“parm = {2}”。
const Hello = (props) => {
console.log(props);
return (<h2>h2 with function component {props.parm}</h2>);
}
ReactDOM.render(<Hello parm={2} />, document.getElementById('mydiv'));
我的问题是,如何将 parm 从 html 传递到 Hello() 组件?请注意,我必须关闭 CORS 进行本地测试, https://alfilatov.com/posts/run-chrome-without-cors/
解决方案
当然,这是可能的。
注意:我不确定您的用例是什么。也许您正在“喷洒”对现有项目的反应?如果您不是,我建议您查看React 文档,因为它们可能会建议一种更好的方法来实现您的结果。
无论如何,这是一个实现您所要求的示例。请注意,您的 HTML 参数已记录到控制台。然后你可以在 react 中使用它。
https://codesandbox.io/s/params-to-react-from-html-lycqx?fontsize=14&hidenavigation=1&theme=dark
// here's how to get the value itself
const myParam = document
.querySelector("#my_container") // get the html element, e.g. a div
.getAttribute("myParam"); // get the value of the custom property on that element
希望能帮助到你!
推荐阅读
- python - 有没有办法保留宏并只更新python中的汇合表?
- flutter - 转换列表
列出 - c++ - C++ 如何处理 const 标记的通过引用传递的类,这些类不是直接更改而是从另一端更改的?
- python - 如何在另一个小部件事件处理程序中访问小部件:Tkinter
- javascript - 创建 $() Jquery 变成纯 Javascript
- spring-boot - 当我定义数据源时,server.xml datesource 和 application.properties 有什么区别
- python - + 和 np.add() 之间的区别
- python - Discord.py:第 343 行,在 _run_event 中等待 coro(*args, **kwargs) TypeError: on_message_edit() 采用 1 个位置参数,但给出了 2 个
- javascript - 出现未解决的错误:使用 React 时输入是无效元素标记
- font-size - Firefox中不同大小的字体