React- 基础

安装

安装React

yarn global add create-react-app或

npm install -g create-react-app
React - 图1

React - 图2

创建React应用

create-react-app react-app

React - 图3

运行应用

yarn run start
React - 图4

JSX语法

JSX语法中,如果我们要使用自己创建的组件,组件开头必须大写

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import TodoList from './TodoList'
  4. import * as serviceWorker from './serviceWorker';
  5. // JSX 语法 <App/> 如果我们要使用自己创建的组件,组件开头必须大写
  6. ReactDOM.render(
  7. <React.StrictMode>
  8. <TodoList />
  9. </React.StrictMode>,
  10. document.getElementById('root')
  11. );

Fragment占位符

使用 占位符解决最外层多一层div嵌套的问题

React - 图5

  1. import React,{Component,Fragment} from 'react'
  2. class TodoList extends Component{
  3. render(){
  4. return(
  5. <Fragment>
  6. <div><input/><button>提交</button></div>
  7. <ul>
  8. <li>学英语</li>
  9. <li>Learning React</li>
  10. </ul>
  11. </Fragment>
  12. )
  13. }
  14. }
  15. // 导出组件
  16. export default TodoList;

React - 图6

响应式设计和事件绑定

改变this指向

通过es6的bind改变this指向

  1. onChange={this.handleInputChange.bind(this)}
  1. //es6 写法
  2. handleAdd=()=>{
  3. this.setState({
  4. count: this.state.count + 1
  5. })
  6. }
  7. //bind 传递this
  8. handleClick(){
  9. this.setState({
  10. count: this.state.count + 1
  11. })
  12. }
  13. //渲染函数
  14. render() {
  15. return <div style={{padding: 50}}>
  16. <p>React 生命周期</p>
  17. <button onClick={this.handleAdd}>点击一下</button>
  18. <button onClick={this.handleClick.bind(this)}>点击一下</button>
  19. <p>{this.state.count}</p>
  20. <Child name="Jack"></Child>
  21. </div>
  22. }

State状态管理

  1. import React,{Component,Fragment} from 'react'
  2. //使用</Fragment> 占位符解决最外层多一层div嵌套的问题
  3. class TodoList extends Component{
  4. //构造函数
  5. constructor(props){
  6. super(props);
  7. //state中定义数据
  8. this.state ={
  9. inputValue:'',
  10. list:[]
  11. }
  12. }
  13. render(){
  14. return(
  15. <Fragment>
  16. <div>
  17. <input value={this.state.inputValue}
  18. onChange={this.handleInputChange.bind(this)}
  19. />
  20. <button onClick={this.handleBtnClick.bind(this)} >提交</button>
  21. </div>
  22. <ul >
  23. {
  24. this.state.list.map((item, index)=>{
  25. return(
  26. <li key={index}
  27. onClick={this.handleItemDelete.bind(this,index)}
  28. >
  29. {item}
  30. </li>
  31. )
  32. })
  33. }
  34. </ul>
  35. </Fragment>
  36. )
  37. }
  38. handleInputChange(e){
  39. //console.log(e.target.value);
  40. //this is undefined,通过es6的bind更改this指向
  41. //错误,通过setState更改数据状态
  42. //this.setstState.inputValue = e.target.value
  43. //setState更改数据
  44. this.setState({
  45. inputValue: e.target.value
  46. })
  47. }
  48. handleBtnClick(){
  49. this.setState({
  50. //添加数据
  51. list:[...this.state.list,this.state.inputValue],
  52. //清空数据
  53. inputValue:''
  54. })
  55. }
  56. handleItemDelete(index){
  57. // immutable
  58. // state 不允许我们直接修改数据
  59. // 错误写法:this.state.list.splice(index,1)
  60. const list = [...this.state.list]
  61. list.splice(index, 1)
  62. this.setState({
  63. list:list
  64. })
  65. }
  66. }
  67. // 导出组件
  68. export default TodoList;

this.setState异步函数

this.setState是一个异步函数,并不一定会立即执行

  1. handleBtnClick() {
  2. this.setState((prevState) => ({
  3. list: [
  4. ...prevState.list,
  5. prevState.inputValue
  6. ],
  7. inputValue: ''
  8. }))
  9. console.log(`AAA`)
  10. }

this.setState 是异步函数,不一定在console.log之前执行。

即想要this.setState执行后在执行console.log()

  1. this.setState((prevState) => ({
  2. list: [
  3. ...prevState.list,
  4. prevState.inputValue
  5. ],
  6. inputValue: ''
  7. }),() => {
  8. console.log(`AAA`)
  9. })
  10. }

不转义标签内容

使用dangerouslySetInnerHTML不转义<h1>Test</h1>

React - 图7

  1. {
  2. this.state.list.map((item, index)=>{
  3. return(
  4. <li key={index}
  5. onClick={this.handleItemDelete.bind(this,index)}
  6. dangerouslySetInnerHTML={{__html:item}}
  7. >
  8. </li>
  9. )
  10. })
  11. }

默认写法转义标签

React - 图8

htmlFor 鼠标聚焦输入框

  1. <label htmlFor="insertArea">输入内容</label>
  2. <input
  3. id="insertArea"
  4. className='input'
  5. value={this.state.inputValue}
  6. onChange={this.handleInputChange.bind(this)}
  7. />

组件拆分及传值

组件传值通过属性

子组件通过this.props.xxx接收数据

  1. # 父组件传值
  2. <TodoItem content={item} />
  3. # 子组件接受
  4. import React,{ Component } from 'react'
  5. class TodoItem extends Component{
  6. render(){
  7. return <div>{this.props.content}</div>
  8. }
  9. }
  10. export default TodoItem

子组件触发父组件this.props.fn() 方法

  1. # 父组件
  2. <TodoItem
  3. content={item}
  4. index={index}
  5. deleteItem={this.handleItemDelete.bind(this)}
  6. />
  7. handleItemDelete(index){
  8. const list = [...this.state.list]
  9. list.splice(index, 1)
  10. this.setState({
  11. list:list
  12. })
  13. }
  14. # 子组件
  15. class TodoItem extends Component{
  16. constructor(props){
  17. super(props)
  18. //在复杂组件中这种this写法可以节约一定的性能
  19. this.handleClick = this.handleClick.bind(this)
  20. }
  21. render(){
  22. return(
  23. <div onClick={this.handleClick }>
  24. {this.props.content}
  25. </div>
  26. )
  27. }
  28. handleClick(){
  29. this.props.deleteItem(this.props.index)
  30. }
  31. }
  32. export default TodoItem

代码优化

  • 优化前
  1. render(){
  2. return (
  3. <div onClick={this.handleClick }>
  4. {this.props.content}
  5. </div>
  6. )
  7. }
  8. handleClick(){
  9. this.props.deleteItem(this.props.index)
  10. }
  • 优化后
  1. render(){
  2. // es6语法优化
  3. const {content} = this.props
  4. return (
  5. <div onClick={this.handleClick }>
  6. {content}
  7. </div>
  8. )
  9. }
  10. handleClick(){
  11. const { deleteItem, index } = this.props
  12. deleteItem(index)
  13. }

this.setState

情况一:

  1. this.setState({
  2. inputValue: e.target.value
  3. })
  • 优化后
  1. const value = e.target.value
  2. //直接返回一个对象时写法
  3. this.setState(() => ({
  4. inputValue: value
  5. }))

情况二:

  1. this.setState({
  2. //添加数据
  3. list:[...this.state.list,this.state.inputValue],
  4. //清空数据
  5. inputValue:''
  6. })
  • 优化后
  1. // this.setState可以接收一个参数,修改之前的参数
  2. this.setState((prevState) => ({
  3. list: [...prevState.list, prevState.inputValue],
  4. inputValue: ''
  5. }))

情况三:

  1. handleItemDelete(index){
  2. const list = [...this.state.list]
  3. list.splice(index, 1)
  4. this.setState({
  5. list:list
  6. })
  7. }
  • 优化后
  1. handleItemDelete(index){
  2. this.setState((prevState) => {
  3. const list = [...prevState.list]
  4. list.splice(index, 1)
  5. return { list }
  6. })
  7. }

PropTypes与defaultProps

  1. //指定传递参数的数据类型,类型校验
  2. TodoItem.propTypes = {
  3. test: PropTypes.string.isRequired,
  4. content: PropTypes.string,
  5. deleteItem: PropTypes.func,
  6. index: PropTypes.number
  7. }
  8. //参数默认值
  9. TodoItem.defaultProps = {
  10. test: 'hello world'
  11. }

Props,State与render函数

react数据驱动

  1. - 当组件的`state`或者`props`发生改变的时候,`render`函数就会重新执行
  • 当父组件的render函数被执行时,子组件的render函数都将被重新运行一次虚拟DOM

    虚拟DOM 本质上就是一个js对象,用它来描述真实DOM(损耗性能)。

Ref

ref操作dom

React生命周期

  1. 生命周期函数☞在某一时刻会自动执行的函数

React - 图9

初始化

生命周期函数初始化顺序

  1. import React, {Component} from 'react'
  2. class LifeCycle extends Component {
  3. //es6函数,非React生命周期函数,但是会被自动执行
  4. constructor(props) {
  5. super(props)
  6. //定义state
  7. this.state = {
  8. notify: '我是一个通知消息'
  9. }
  10. }
  11. //组件将要挂载时候触发的生命周期函数
  12. componentWillMount(){
  13. console.log('1.组件将要挂载')
  14. }
  15. render(){
  16. console.log('2.数据渲染render')
  17. return(
  18. <div>
  19. 生命周期函数演示
  20. </div>
  21. )}
  22. //组件挂载完成时候触发的生命周期函数
  23. componentDidMount(){
  24. console.log('3.组件挂载完成')
  25. }
  26. }
  27. export default LifeCycle

控制台输出:

React - 图10

警告是本地react版本较新,componentWillMount has been renamed.

React生命周期

React - 图11

React v16.4生命周期

React - 图12

  1. //一个组件要从父组件接受参数
  2. //只要父组件的render函数被重新执行,子组件的这个生命周期就会被执行
  3. componentWillReceiveProps(){
  4. console.log('child componentWillReceiveProps')
  5. }