R_基础_2

1 组件


  1 说白了就是一个独立的标签元素   // 具有可复用性

  2 常用的创建组件的方式有俩种   // 类组件 + 函数式组件

  3 组件文件名, 要以大写字母开头

  4 函数式组件中 props 和 方法调用不需要加 this   // 类组件中需要加 this

  5 函数式组件性能优于类组件   // 但是需要 HOOK 才可以具备, 数据等状态

  6 import {Fragment} from 'react'  // 性能优化 --> 用于包裹视图结构的空标签

  7 注意不要直接修改 props 获取的外部数据值

  8 组件实例 --> import A1 from './A1' --> <A1/>

2 类组件


------------------------------------------ 1 说明 -----------------------------------------

  1 在 constructor 中要使用 this.props , 必须有 super(props) 方法及参数

  2 constructor 的俩个作用 --> 初始化 state + 绑定方法

  3 constructor 可省略不写 react 会隐式的加一个空的 constructor

  4 类组件继承于 React.Component 这个父类, 从而可以使用父类中提供的方法和属性


------------------------------------------ 2 代码范式 -----------------------------------------

import React from 'react'

class A extends React.Component{
  
  constructor(props) {   // 可省略
    super(props)
    this.state = { msg: 'zhang', ..}   // 1 初始化 state, 变量发生变化, 视图自动更新
    this.log = this.k1.bind(this)  // 2 进行方法绑定, 一般不这样用
  }

  k1 = () => {}   // 事件处理程序
  k2() {}   // 事件处理程序

  render() {
    // do something
    return (
      <div>
        <button onClick={this.log}> 按钮 </button>  // 3 方法调用
      </div>
    )
  }
}

export default A


------------------------------------------ 3 格式(常用) -----------------------------------------

class A extends React.Component{
  state = {hh: '按钮'}   // 定义数据简写

  c1 = this.props => console.log(this.props)   // 也可直接访问 this.props

  render () {
    // do something
    return (<i onClick={this.c1}> {this.state.hh} </i>)
  }
}


------------------------------------------ 4 数据修改(常用) -----------------------------------------

  1 setState() 用于修改 state 定义的私有数据 + 更新 UI   // 数据驱动视图的思想

  2 每次执行 this.setState() 都会触发 diff运算, 自动更新对应节点的视图

  3 render() / constructor() / componentDidUpdate() / 渲染方法中, 不可以使用 this.setState()

  4 通常在功能方法里面, 使用 this.setState()

  5 代码范式 (常用)

    1 定义数据: state = {name: 'zhang', age: 25}

    2 修改数据: this.setState({name: 'wei'}) / this.setState(state => ({age: state.age+1}))  // 判断新值和旧值是否有关

3 函数式组件


const X = props => {   // 极简 --> export default () => ()
  // do something
  const c1 = () => console.log(props)

  return (<i onClick={c1}> 按钮 </i>)
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值