一、Installation
官网installation
安装工具:create-react-app。
在安装工具之前先安装yarn(Mac则运行brew install yarn
即可),如果没有安装会自动降级为npm。
npm install -g create-react-app
create-react-app . // 初始化空目录
yarn start
运行成功的界面
- src 目录,用于存放所有源代码,最重要的就是 index.js 。
- public 目录,用于存放静态资源(不需要 build 的资源),如 publib/index.html。
- build 目录,运行 yarn run build 或者 npm run build 就可以看到 build 目录了。
create-react-app内置了webpack的所有功能,不需要我们配置,所以没有webpack.config.js 文件。
二、Hello React
官网
按照官网教程,把如下代码复制到src/index.js 里的 6~9 行。
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
页面就会出现Hello, world!啦
这里的root就是publib/index.html里面的id。ReactDOM.render(p1, p2) 的作用就是将 p1 插入到 p2 中。只不过 p1 虽然在 JS 文件中,却可以使用 HTML 的语法,这就是JSX语法。
三、部署
git add .
git commit -m 'update'
yarn run build
运行yarn run build
之后,git status没有显示任何文件变动,需要删除.gitignore 里面的 /build这一行。
然后再次运行:
git add .
git commit -m "build"
git push origin master
打开github上的预览链接,我们会发现css、js都请求失败。这是因为我们请求的链接中少了React/build/
这部分。
在我们运行yarn run build
时其实有提示:
yarn run build
于是,就在package.json里面添加:
"homepage": "https://jirengu-inc.github.io/React" // 这里需要改为自己的项目预览地址
再次部署:
yarn run build
git add .
git commit -m "build"
git push origin master
打开预览链接地址,会发现预览依然报错。这次我们会发现预览的地址其实少了/build
。好像发现了点什么,于是把刚刚在package.json里面加的那句后面再加上/build
。
yarn run build
git add .
git commit -m "build again"
git push
打开预览链接,真的就好了呢。