react

1.父子通信

React中是单向数据流,数据只能从父组件通过属性的方式传给其子组件

父传子:props

子传父:子组件通过调用父组件传递到子组件的方法向父组件传递消息的。

2.封装公共组件

首先react公共组件的实现与原生js实现函数基本一致,接受形参,处理数据,返回or不返回一个结果。在不同场景调用组件时,可以通过props属性,传递状态与方法,如果是展示型组件,传入不同样式对象(形参),就可以在不同场景使用多样化展示ui。

3.父组件调用子组件方法

refs

javascript 复制代码
// ChildComponent.js
class ChildComponent extends React.Component {
  doSomething = () => {
    console.log('Child method called');
  };

  render() {
    return <button onClick={this.doSomething}>Call Child Method</button>;
  }
}

// ParentComponent.js
class ParentComponent extends React.Component {
  callChildMethod = ref => {
    if (ref) {
      ref.current.doSomething();
    }
  };

  render() {
    return (
      <div>
        <ChildComponent ref={this.callChildMethod} />
      </div>
    );
  }
}

4.生命周期

componentDidMount: 该方法在组件挂载后立即调用(即插入到DOM树中)。通常用于执行初始设置,例如从API获取数据或设置事件监听器。

componentDidUpdate: 该方法在更新发生后立即调用。每当组件的props或state发生变化时都会触发它。通常用于基于更新后的状态或props执行操作,例如进行额外的API调用。

componentWillUnmount: 该方法在组件即将卸载和销毁之前立即调用。通常用于执行清理操作,例如移除事件监听器或取消任何正在进行的任务

相关推荐
conkl6 分钟前
梅森旋转算法深度解析:构建更健壮的前端请求体系
前端·算法·状态模式
程序定小飞8 分钟前
基于SpringBoot+Vue的常规应急物资管理系统的设计与实现
java·开发语言·vue.js·spring boot·后端·spring
z***39621 小时前
Plugin ‘org.springframework.bootspring-boot-maven-plugin‘ not found(已解决)
java·前端·maven
e***58231 小时前
Nginx 配置前端后端服务
运维·前端·nginx
小奶包他干奶奶1 小时前
Webpack学习——Plugin(插件)
前端·学习·webpack
张拭心1 小时前
AI 从业者需要铭记的时刻:2023年6月30日
前端·ai编程
我叫张小白。1 小时前
Vue3 Hooks:逻辑复用的解决方案
前端·javascript·vue.js·前端框架·vue
S***t7141 小时前
前端物联网开发
前端·物联网
我叫张小白。1 小时前
Vue3 Props 的使用:组件间数据传递的桥梁
前端·javascript·vue.js·vue3
r***86981 小时前
Nginx解决前端跨域问题
运维·前端·nginx