自学内容网 自学内容网

React速成

 

 

 

 

useRef获取DOM 

 组件通讯

 子传父

function Son({ onGetMsg }){
  const sonMsg = 'this is son msg'
  return (
    <div>
      {/* 在子组件中执行父组件传递过来的函数 */}
      <button onClick={()=>onGetMsg(sonMsg)}>send</button>
    </div>
  )
}


function App(){
  const getMsg = (msg)=>console.log(msg)
  
  return (
    <div>
      {/* 传递父组件中的函数到子组件 */}
       <Son onGetMsg={ getMsg }/>
    </div>
  )
}

 兄弟组件——状态提升


// 1. 通过子传父 A -> App
// 2. 通过父传子 App -> B

import { useState } from "react"

function A ({ onGetAName }) {
  // Son组件中的数据
  const name = 'this is A name'
  return (
    <div>
      this is A compnent,
      <button onClick={() => onGetAName(name)}>send</button>
    </div>
  )
}

function B ({ name }) {
  return (
    <div>
      this is B compnent,
      {name}
    </div>
  )
}

function App () {
  const [name, setName] = useState('')
  const getAName = (name) => {
    setName(name)
  }
  return (
    <div>
      this is App
      <A onGetAName={getAName} />
      <B name={name} />
    </div>
  )
}

export default App

 爷孙组件

// App -> A -> B

import { createContext, useContext } from "react"

// 1. createContext方法创建一个上下文对象

const MsgContext = createContext()

function A () {
  return (
    <div>
      this is A component
      <B />
    </div>
  )
}

function B () {
  // 3. 在底层组件 通过useContext钩子函数使用数据
  const msg = useContext(MsgContext)
  return (
    <div>
      this is B compnent,{msg}
    </div>
  )
}

function App () {
  const msg = 'this is app msg'
  return (
    <div>
      {/* 2. 在顶层组件 通过Provider组件提供数据 */}
      <MsgContext.Provider value={msg}>
        this is App
        <A />
      </MsgContext.Provider>
    </div>
  )
}

export default App

useEffect

React中useEffect钩子-CSDN博客

自定义hook

自定义 Hook 是一种在 React 函数组件中重用状态逻辑的方式。它们可以让你将组件逻辑提取到可重用的函数中,从而提高代码的可读性和可维护性。自定义 Hook 的命名通常以 use 开头,并且它们必须接受一个函数参数并返回 React 的状态和函数(例如 useState 和 useEffect 所返回的内容)。

以下是如何创建和使用自定义 Hook 的一个简单示例:

1. 创建一个自定义 Hook

假设我们要创建一个自定义 Hook 来处理用户的登录状态。我们可以创建一个名为 useUserAuth 的 Hook。

import { useState, useEffect } from 'react';  
  
function useUserAuth() {  
  const [isAuthenticated, setIsAuthenticated] = useState(false);  
  
  useEffect(() => {  
    // 这里可以添加一些逻辑,比如检查本地存储、调用 API 等  
    // 假设我们从本地存储中获取登录状态  
    const storedIsAuthenticated = localStorage.getItem('isAuthenticated');  
    if (storedIsAuthenticated === 'true') {  
      setIsAuthenticated(true);  
    }  
  
    // 清理函数(可选)  
    return () => {  
      // 组件卸载时执行的逻辑,比如清除定时器、取消网络请求等  
    };  
  }, []); // 空数组作为依赖项,表示这个 effect 只在组件挂载和卸载时运行一次  
  
  const login = () => {  
    setIsAuthenticated(true);  
    localStorage.setItem('isAuthenticated', 'true');  
  };  
  
  const logout = () => {  
    setIsAuthenticated(false);  
    localStorage.setItem('isAuthenticated', 'false');  
  };  
  
  return { isAuthenticated, login, logout };  
}  
  
export default useUserAuth;

2. 使用自定义 Hook

现在,我们可以在任何组件中使用这个自定义 Hook。

import React from 'react';  
import useUserAuth from './useUserAuth'; // 假设 useUserAuth 在同一个目录下  
  
function App() {  
  const { isAuthenticated, login, logout } = useUserAuth();  
  
  return (  
    <div>  
      <h1>User Authentication</h1>  
      {isAuthenticated ? (  
        <button onClick={logout}>Logout</button>  
      ) : (  
        <button onClick={login}>Login</button>  
      )}  
      <p>You are {isAuthenticated ? 'logged in' : 'logged out'}</p>  
    </div>  
  );  
}  
  
export default App;

注意事项

  1. 命名规范:自定义 Hook 的命名应该以 use 开头,这有助于 React 和其他开发者识别出这是一个 Hook。
  2. 避免在类组件中使用:自定义 Hook 只能在函数组件和自定义 Hook 中使用,不能在类组件中使用。
  3. 副作用:在自定义 Hook 中使用 useEffect 来处理副作用,比如数据获取、订阅或手动更改 React 组件中的 DOM。
  4. 状态提升:当多个组件需要共享状态时,可以将这些状态提升到一个共同的父组件中,或者使用全局状态管理解决方案(如 Redux)。自定义 Hook 可以帮助封装和重用这些状态逻辑。

通过自定义 Hook,你可以更好地组织你的代码,使其更具可读性和可维护性。


原文地址:https://blog.csdn.net/m0_55049655/article/details/142830190

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!