2021年12月4日
react学习day1
React介绍:
由facebook推出的数据驱动JS库
基于MVC灵感设计(vue是基于mvvm)
特性:数据驱动 最小粒度更新(diff/fiber) 组件化
React项目创建:
1. 下载安装脚手架
yarn global add create-react-app
2. 创建项目
create-react-app 项目名(项目名及路径不能有中文)
3. 启动项目(react服务器端口默认3000)
cd 项目名
yarn start || npm run start
JSX模板语法糖:
允许在JS中混写HTML标记,每一段在JS中的HTML标记,它就是一个小的JSX
(
es字符串模板语法 <div>${xxx}</div>
template模板语法 {{ xxx }}
jsx模板语法 { xxx }
)
模板语法:可以在当前模板中,嵌入一些变量或者函数等动态数据..
JSX底层:
JSX是语法糖,所以写的每一个JSX标记(template中的节点),都会被转译为虚拟DOM节点
//当把JSX节点转译成虚拟DOM时,会把中间{}中的值替换为真正的值
<div>{ city }</div> === React.createElement('div', div的属性,'city真正的值')
JSX的特性:
1. JSX中采用的是{}进行占位,在{}中可以书写任意表达式
2. JSX不同于HTML,它的事件绑定采用的是驼峰
例: <button onClick={ 要触发的函数名 } ></button>
3. 动态属性绑定,采用{}进行占位!!!(react所见即所得,哪里要动哪里就加占位符)
例: <button id={xxxx} name={xxxx} />
4. class是js中的关键字,所以绑定class是采用className别名
5. style必须给一个对象,不支持字符串
例: <h1 style={ {color: 'xxx', fontWeight: 'xxx' } }>111</h1>
组件化开发:
React自定义组件创建:
1. 引入核心模块(React项目中,一个组件就是一个.js文件,
组件.js,组件文件首字母大写 )
import React from ‘react’
2. 组件创建并定义视图
class 组件名(首字母大写) extends React.Component {
render(){
return <div>
组件视图定义再此处 //类似template
</div>
}
}
3. 暴露
export default 组件名
React组件的使用:
1. 引入自定义组件
import 自定义组件名 from './组件文件路径'
2. 使用标签直接渲染
<自定义组件名/> //单双标签都支持
组件状态:
每个组件内部需要变化的动态数据,就叫组件状态
在react中,叫state (在vue中,叫data)
1. 状态定义
class 组件 extends xxx {
state = {
状态名: 状态值
}
render(){
...
}
}
2. 获取状态的值
JS中: this.state.状态名
JSX中: {this.state.状态名}
class 组件 extends xxx {
state = {
状态名: 状态值,
city: '贵阳市'
}
render(){
//进阶取值方式,解构
let { city } = this.state
return <div>
<p>我的家乡是: {this.state.city}</p>
<p>解构取值: {city}</p>
</div>
}
}
3. 改变状态的值
//注意在自定义函数中,this指向问题!!!!!!
REACT是基于MVC写出来的,所以没有监听数据变化!!!必须使用setState改变状态,通知视图自动更新
this.setState({
状态名: 新的值
})
//每个组件身上都有setState函数,任何组件状态改变都要用此函数!!!
//setState做了2件事:1. 改变state数据 2. 通知视图最小粒度更新
Hi there, every time i used to check webpage posts here in the
early hours in the dawn, since i love to learn more and more.
You actually make it appear so easy together with your presentation however I in finding this matter to be actually
one thing which I think I would by no means understand.
It seems too complex and extremely wide for me.
I’m taking a look forward for your subsequent put up, I’ll try to get the grasp of it!
I know this site offers quality depending articles or reviews and other material, is
there any other web site which presents these kinds of stuff in quality?
This information is worth everyone’s attention. When can I find out more?
I like the valuable information you provide in your articles.
I’ll bookmark your blog and check again here regularly. I am quite certain I will learn many new
stuff right here! Good luck for the next!
I got this web site from my buddy who informed me concerning this web page and
now this time I am browsing this website and reading very informative articles at this time.