Vue到React (函数式组件)丝滑过渡

58 阅读4分钟

vue必备知识点

  • 组件化思想
  • 插值语法
  • 样式绑定
    • class
    • style
  • 插槽
    • 默认插槽
    • 具名插槽
    • 作用域插槽
  • 组件数据传递
    • props/emit/ref/defineExpose
    • provide/inject
    • vuex
  • 事件绑定
    • 原生事件 (@click)
    • 自定义事件(@eventName)
  • 指令:
    • v-if
    • v-for
    • v-bind
    • v-text
    • v-html
  • 数据响应式
    • ref
    • reactive
  • 生命周期
    • setup
    • onMounted
    • onUnmounted
  • 计算属性:computed
  • 数据监听器:watch

如果以上你都掌握了,那么使用React如喝水般简单!!!!

在React中使用

组件化思想

React 也强调组件化,但组件的定义方式是通过 JavaScript 类或函数。React 组件通常使用 JSX 语法来描述 UI

//声明一个函数式组件
export default function ChildrenCom(){
  return (
    <div>我是子组件</div>
  )
}
import ChildrenCom from './ChildrenCom.jsx'
function Father(){
  return (
    <div>
      我是父组件
      <ChildrenCom />
    </div>
  )
}

插值语法

Vue中使用 {{ }} 动态解析 React中使用 { } 动态解析其值

function WishCom(){
  const myWish = '我希望在新的一年,大家平安健康,幸福发财'
  return (
    <div>
      <h1>我的新年愿望:</h1>
      <p>{myWish}</p>
    </div>
  )
}

样式绑定

React中使用className 绑定类样式

  • 直接使用字符串
.wishColor{
  color:red;
}
function WishCom(){
  return (
    <div>
      <span className="wishColor">好日子</span>
      <span>还在后面呢!</span>
    </div>
  )
}

  • 动态类名
function WishCom(){
  const year = 2025 
  return (
    <div>
      <span >日子就应该</span>
      <span className={year === 2025?'wishColor':''}>红红火火!</span>
      // 也可以采用``模版字符串
      <span className={`${year === 2025?'wishColor':''}`}>红红火火!</span>
    </div>
  )
}

  • 行内样式

行内样式通过 style 属性传递一个 JavaScript 对象,对象的键是 CSS 属性名,值是 CSS 属性值。

CSS 属性名需要使用驼峰命名法(如 fontSize 而不是 font-size)

function ImpracticalCom(){
  /*
    const style = {
    color:'red',
    fontSize:30
    }
  */
  return (
    <div>
      <span style={{color:'red',fontSize:30}}>新年快乐</span>
    </div>
  )
}

插槽

  • 默认插槽

当将内容嵌套在 JSX 标签中时,子组件将在名为 children 的 prop 中接收到该内容

//子组件
function ChildrenCom(props) {
  const { children } = props;
  return (
    <>
      <div>我是子组件</div>
      <span>我的爱好:</span>
      {children ?? <span>看书、学习、运动 </span>}
    </>
  );
}
// 父组件
function FatherCom() {
  return (
    <div>
      <span>我是父组件</span>
      <ChildrenCom />
      <hr/>
      <ChildrenCom >
        <span>吃饭、睡觉、打豆豆</span>
      </ChildrenCom>
    </div>
  );
}

  • 具名插槽

在React中,没有直接的“具名插槽”概念,但可以通过传递 props 来实现类似功能

// 子组件
function ChildrenCom(props) {
  const { header, footer } = props;
  return (
    <div>
      <div>{header}</div>
      <div>我是子组件的内容</div>
      <div>{footer}</div>
    </div>
  );
}

// 父组件
function Father() {
  return (
    <ChildrenCom
      header={<h1>我是头部</h1>}
      footer={<p>我是底部</p>}
      />
  );
}

  • 作用域插槽

React 中可以通过传递函数作为 props 来实现类似作用域插槽

// 子组件
export default function ChildrenCom(props) {
  const { renderContent } = props;
  const data = { message: "这是子组件的数据" };
  return (
    <div>
      <div>我是子组件</div>
      {renderContent(data)}
    </div>
  );
}

// 父组件
function Father() {
  return (
    <ChildrenCom
      renderContent={({ message }) => <p>{message}</p>}
      />
  );
}

数据传递

  • props/emit

React中通过 props 传递数据,通过传递函数作为 props 来实现子组件向父组件通信

// 子组件
function ChildrenCom(props) {
  const { onButtonClick } = props;
  return (
    <div>
      <button onClick={() => onButtonClick("Hello from child!")}>
        点击我
      </button>
    </div>
  );
}

// 父组件
function Father() {
  const handleChildClick = (message) => {
    console.log(message); // 输出:Hello from child!
  };

  return (
    <div>
      <ChildrenCom onButtonClick={handleChildClick} />
    </div>
  );
}
  • provide/inject

React 中通过 Context 来实现类型Vue 的 provide/inject 功能

import React, { useContext } from "react";

// 创建 Context
const countContext = React.createContext(100);
const FatherCom = () => {
  return (
    <div>
      <countContext.Provider value={1000}>
        <ChildrenCom />
      </countContext.Provider>
    </div>
  );
};

const ChildrenCom = () => {
  const count = useContext(countContext);
  return <div>{count}</div>;
};

事件绑定

  • 原生事件

React 中通过 onClickonChange 等属性绑定原生事件。

function ButtonCom() {
  const handleClick = () => {
    console.log("按钮被点击了");
  };
  const senMessageHandle = (message)=>{
    console.log(message)
  }
  return (
    <>
      <button onClick={handleClick}>点击我</button>
      <button onClick={()=>senMessageHandle('hello world')}>点击我</button>
    </>
  );
}
  • 自定义事件

React 中通过传递函数作为 props 来实现自定义事件。

// 子组件
function ChildrenCom(props) {
  const { onCustomEvent } = props;
  return (
    <button onClick={() => onCustomEvent("自定义事件触发")}>
      触发自定义事件
    </button>
  );
}

// 父组件
function Father() {
  const handleCustomEvent = (message) => {
    console.log(message); // 输出:自定义事件触发
  };

  return (
    <ChildrenCom onCustomEvent={handleCustomEvent} />
  );
}

指令

  • v-if

React 中使用条件渲染来实现类似 v-if 的功能。

function ConditionalCom() {
  const isShow = true; //不能用数字 0 做否定条件 会显示0
  return (
    <div>
      {isShow && <p>这段内容会显示</p>}
      {isShow ? <p>这段内容会显示</p>:<p>这段内容不会显示</p>}
    </div>
  );
}
  • v-for

React 中使用 map 方法来实现类似 v-for 的功能。

function ListCom() {
  const items = ["苹果", "香蕉", "橙子"];
  return (
    <ul>
      {items.map((item, index) => (
      <li key={index}>{item}</li>
    ))}
    </ul>
  );
}
  • v-bind

React 中通过 {} 动态绑定属性。


function ChildCom(props){
  const {title} = props
  return (
    <h1>{title}</h1>
  )
}
function BindCom() {
  const url = "https://react.docschina.org/";
  const childComTitle = '子组件'
  return (
    <>
      <a href={url}>让我们开始学习react吧</a>
      <ChildCom title={childComTitle} />
    </>
  );
}
  • v-html
function HtmlCom() {
  const htmlContent = "<p>这是一段 HTML 内容</p>";
  return (
    <div dangerouslySetInnerHTML={{ __html: htmlContent }} />
  );
}

数据响应式

  • ref / reactive

React 中使用 useState 来维护数据状态。

import { useState } from 'react';

function UseStateCom() {
  const [count,setCount] = useState(1)
  const incrementCountHandle = ()=>{
    
    // const _count = count + 1
    // setCount(_count)
    setCount(pre=>pre+1)
  }
  return (
    <div>
      <span>{count}</span>
      <button onClick={incrementCountHandle}>点我+1</button>
    </div>
  );
}

计算属性

React 中使用 useMemo 来实现类似计算属性的功能。

import { useMemo } from 'react';

function ComputedCom() {
  
  const [count, setCount] = useState(0);
  const doubleCount = useMemo(() => count * 2, [count]);

  return (
    <div>
      <p>{doubleCount}</p>
      <button onClick={() => setCount(count + 1)}>增加</button>
    </div>
  );
}

数据监听器

import { useEffect, useState } from 'react';

function WatchCom() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("count 发生了变化:", count);
    // todo 网络请求 数据处理 
  }, [count]);

  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>增加</button>
    </div>
  );
}

生命周期

在React中 useEffect 包含了 组件的挂载 更新 卸载

import { useEffect } from 'react';

function LifecycleCom() {
  useEffect(() => {
    console.log("组件挂载");
    return () => {
      console.log("组件卸载");
    };
  }, []);

  return <div>生命周期示例</div>;
}