我想在静态 HTML 页面的一个 div 中添加一个 React 组件。我这样做而不是将整个页面转换为 React,因为我只需要对网页的少数部分使用 React。我按照 https://reactjs.org/docs/add-react-to-a-website.html 上的说明进行操作。我的问题是:
- 这样做可以吗,还是建议我完全用 React 实现我的网站?
- 我做了上述页面告诉我的事情,但是当我在浏览器上显示我使用React的部分时,它没有得到实现(我的IDE是WebStorm)。是否有一个特定的脚本(例如使用 React 框架时的yarn start)我必须运行才能编译?
最佳答案
查看这个最小的示例。您需要包含 3 个脚本
- react.development.js (the react lib)
- react-dom.development.js (react lib to interact with dom)
- babel.min.js (converts react JSX into browser compatible JS)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<!-- Don't use this in production: -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
function HelloWorld(props){
return <h1>{`Hello, world! ${props.name}`}</h1>;
}
ReactDOM.render(
<HelloWorld name="James"/>,
document.getElementById('root')
);
</script>
</body>
</html>
注意:这是尝试 React 的好方法,但它不适合生产。 它在浏览器中使用 Babel 缓慢编译 JSX,并使用 React 的大型开发构建。
阅读本节,了解 JSX 的生产就绪设置:
https://reactjs.org/docs/add-react-to-a-website.html#add-jsx-to-a-project在较大的项目中,您可以使用集成工具链 改为包含 JSX:
https://reactjs.org/docs/create-a-new-react-app.html- 您也可以在没有 JSX 的情况下使用 React,在这种情况下您可以删除 通天塔:https://reactjs.org/docs/react-without-jsx.html
来源:https://raw.githubusercontent.com/reactjs/reactjs.org/master/static/html/single-file-example.html
关于javascript - 添加react到静态html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58949220/