搭建React开发环境之前的准备工作
1、必须安装nodejs 注意:安装nodejs稳定版本
2、安装cnpm用cnpm替代npm
地址:http://npm.taobao.org/
安装cnpm: npm install -g cnpm --registry=https://registry.npm.taobao.org
3、用yarn替代npm
第二种方法:cnpm install -g yarn 或者 npm install -g yarn
创建项目
安装脚手架工具 (单文件组件项目生成工具) 只需要安装一次
npm install -g create-react-app / cnpm install -g create-react-app
找到项目要创建的目录执行(手表右键+shift),下面的reactdemo是项目名称,在powershell里输入:
npx create-react-app reactdemo
构建React-app应用时create-react-app卡住超慢的解决办法:https://blog.csdn.net/qq_40197828/article/details/86823985
运行项目/发布项目
npm start 运行项目(调试)/ npm run build 生成项目(发布)
React里的注意事项
1、所有的模板要被一个根节点包含起来
2、模板元素不要加引号
3、{}绑定数据
4、绑定属性注意:
class 要变成 className
for 要变成 htmlFor
style属性和以前的写法有些不一样
<div style={{'color':'blue'}}>{this.state.title}</div>
<div style={{'color':this.state.color}}>{this.state.title}</div>
5、循环数据要加key
6、组件的构造函数中一定要注意 super
子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象
constructor(props){
super(props); /*用于父子组件传值 固定写法*/
this.state={
userinfo:'w'w'w'
}
}
7、组件名称首字母大写、组件类名称首字母大写
绑定事件处理函数this的几种方法:
第一种方法:
run(){
alert(this.state.name)
}
<button onClick={this.run.bind(this)}>按钮</button>
第二种方法:
构造函数中改变
this.run = this.run.bind(this);
run(){
alert(this.state.name)
}
<button onClick={this.run>按钮</button>
第三种方法(用的较多):
run=()=> {
alert(this.state.name)
}
<button onClick={this.run>按钮</button>