1.什么是react
1.1 react 介绍
1.用于构建用户界面的JavaScript库,
2.主要构建UI,很多人认为 React 是 MVC 中的 V(视图)
3.拥有较高的性能,代码逻辑简单
1.2 react的特点
1.声明式:采用声明范式,描述应用
2.高效:对DOM进行模拟,最大程度减少与DOM的交互
3.灵活:可以和很多框架配合
4.组件:构建组件,可重复使用
2.react脚手架
npx create-react-app 项目名
2.1 npx的作用:
1.默认情况下,首先检查路径中是否存在要执行的包(即在项目中);
2.如果存在,它将执行;
3.若不存在,意味着尚未安装该软件包,npx将安装其最新版本,然后执行它;
启动命令
npm run start
导入REACT和REACT-DOM两个包
import react from 'react'
import ReactDom from 'react-dom'
创建元素
const p=react.createElement('p',null,'内容')
在页面中显示
reactDom.render(p,document.querySelector('#root'))
3.jsx使用
3.1 什么是jsx
jsx是一种JavaScript的语法扩展,运用在react架构中,在JavaScript内部实现,元素是构成react应用的最小单位,jsx就是声明react当中的元素,react使用jsx描述用户界面
简单 用法:
let ul =
<ul>
<li>第一个li</li>
<li>第二个li</li>
<li>第三个li</li>
</ul>
ReactDom.render(ul, document.querySelector('#root'))
脚手架创建的项目中可以使用jsx
3.2 jsx属性写法
1.元素属性名必须使用驼峰命名法
2.特殊属性名:class>className ,for>htmlFor
在src中创建一个css文件夹,在写css
在index.js中使用import引入css文件
在行内写样式用{{}}
<li style={{'color':'blue'}}>第一个li</li>
3.3 循环渲染
const dataList = [
{ id: 1, title: '循环1' },
{ id: 2, title: '循环2' },
{ id: 3, title: '循环3' },
]
let ul = (<ul className='list'>
{dataList.map(item => <li key={item.id}>{item.title}</li>)}
</ul>
reactDom.render(ul,document.querySelector('#root'))
)
3.5 样式
<li key={item.id} style={'color':'red','backgroundColor':'blue'}>{item.title}</li>)}
3.4 总结
1.jsx是react的核心
2.jsx是在js代码中写html结构,是react声明式的体现
3.使用className给jsx添加样式
4.react组件
4.1 函数组件
function Hello () {
return (
<p>这是组件</p>
)
}
ReactDom.render(<Hello />, document.querySelector('#root'))
函数组件用<>包裹
4.2 类组件
class App extends Component {
render () {
return (
<h1>hello word</h1>
)
}
}
ReactDom.render(<App />, document.querySelector('#root'))
注意:
类名称必须大写字母开头
类组件应该继承react.Component父类,从而可以使用父类提供的方法或者属性
类组件必须提供render
render必须有返回值
4.3 单文件组件
1.新建组件页面,把写好的组件放进来
2.export 导出
3.import 引入
4.4 react 组件传值
子页面
<h1>{this.props.title}</h1>
父页面
<App title="props 的值" />
4.5 react事件
class App extends Component {
render () {
console.log(this.props)
return (
<h1 onClick={this.changeColor}>{this.props.title}</h1>
)
}
changeColor (e) {
console.log('点击')
}
}
4.6 组件状态
类组件是有状态组件,函数组件是无状态组件
- state是数据,是组件内部私有数据,只能在组件内部使用
- state的值是对象,表示一个组件中可以有多个数据
- 通过this.state获取数据
state = {
username: 'onlifes'
}
<h1>{this.state.username}</h1>
改变状态
changeColor = () => {
this.setState({
username: '改过的username'
})
}
4.6.1 计数器组件
import React, { Component } from 'react'
class Compont extends Component {
state = {
count: 0
}
render () {
return (
<div>
<p>计数器:{this.state.count}</p>
<button onClick={this.countUP}>+1</button>
<button onClick={this.countDown}>-1</button>
</div>
)
}
countUP = () => {
this.setState({
count: this.state.count + 1
})
}
countDown = () => {
this.setState({
count: this.state.count - 1
})
}
}
export default Compont