[英]How do I pass data from html/JavaScript page to a React Component
I have a working react application.我有一个有效的反应应用程序。 If I render the component on the bottom of App.js
, it works.如果我在App.js
的底部渲染组件,它就可以工作。 It bundles everything together.它将所有东西捆绑在一起。
However, I would like to render the react component in the file that includes bundle.js
.但是,我想在包含bundle.js
的文件中呈现反应组件。
So on the HTML page I have this code:所以在 HTML 页面上我有这段代码:
<script src="Scripts/ParsedRequests/dist/bundle.js"></script>
<script>
var props = {
rowData: { make: 'Toyota2', model: 'Celica', price: 35000 }
};
console.log(props);
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(React.createElement(Main, props, null));
</script>
The error I am getting is: ReactDOM is not defined
我收到的错误是: ReactDOM is not defined
You should add the JS libraries in your HTML file, React
and ReactDOM
, so you can use the functions in your JS code.你应该在你的 HTML 文件中添加 JS 库, React
和ReactDOM
,这样你就可以在你的 JS 代码中使用这些函数。
<div id="root"></div> <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script> <script type="text/babel"> var props = { rowData: { make: 'Toyota2', model: 'Celica', price: 35000 } }; function Main(props) { console.log(props); return ( <div> Make: {props.rowData.make}<br />Model: {props.rowData.model}<br />Price: {props.rowData.price} </div> ); } const container = document.getElementById('root'); const root = ReactDOM.createRoot(container); root.render(React.createElement(Main, props, null)); </script>
You can read more about it on the official doc: https://reactjs.org/docs/add-react-to-a-website.html您可以在官方文档上阅读更多相关信息: https ://reactjs.org/docs/add-react-to-a-website.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.