首页 > 解决方案 > 如何将 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/

标签: reactjs

解决方案


当然,这是可能的。

注意:我不确定您的用例是什么。也许您正在“喷洒”对现有项目的反应?如果您不是,我建议您查看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

希望能帮助到你!


推荐阅读