useContext
用于实现跨组件通信
src/context/index.ts// 用于创建上下文对象import { createContext } from 'react'const context = createContext(0)export default context
import React from 'react'import context from './context' // 引入export default function App() {const [money] = React.useState(8888)return (<div><h1 >title</h1><context.Provider value={money}><Father /></context.Provider></div>);}function Father() {return (<div><Son /></div>)}function Son() {return (<div><Grandson /></div>)}// import {useContext} from 'react'function Grandson() {const Money = React.useContext(context) // 写法1return (<div><p> {Money} </p> {/* 写法1 */}<p> {React.useContext(context)} </p></div>)}
useRef
用于实现ref绑定
类组件中的ref绑定
<h1 ref={el=>this.H1=el}>title</h1>
useRef获取元素
import React from 'react'export default function App() {const h1Ref: any = React.useRef(null);console.log(h1Ref) // {current: null}const change = () => {console.log(h1Ref) // {current: h1}h1Ref.current.style.color = 'red'}return (<div><h1 ref={h1Ref}>title</h1><button onClick={change}>onClick here change title color</button></div>);}
useRef获取类组件
- 案例:在App组件中修改Hello组件的state
操作和useRef获取元素相同
import React from 'react'export default function App() {const ChildRef:any=React.useRef(null)const change=()=>{// 通过ref绑定获取Child组件的setFn方法console.log(ChildRef)// {current: Child {props: {…}, context: {…}, refs: {…}, updater: {…}, setFn: ƒ, …}}ChildRef.current.setFn()}return (<div><button onClick={change}> click </button><Child ref={ChildRef}/></div>);}interface P {}interface S {Componentname: string}class Child extends React.Component<P, S> {constructor(props: P) {super(props)this.state = {Componentname: 'Child'}}setFn = () => {this.setState({Componentname: this.state.Componentname + '.'})}render() {return (<div><p>{this.state.Componentname}</p></div>)}}
useRef获取类组件
ref不能绑定函数组件,但是可以绑定类组件。React提供了React.forwardRef() ,用于解决此问题,该函数调用后返回一个类组件
React.forwardRef 会创建一个React组件,这个组件能够将其接受的 ref 属性转发到其组件树下的另一个组件中。
React.forwardRef 接受渲染函数作为参数。React 将使用 props 和 ref 作为参数来调用此函数。此函数应返回 React 节点。
// Child组件定义:import React,{forwardRef} from 'react'function Child() {const Fn = () => {console.log(1)}return (<div>Child</div>)}export default forwardRef(Child)//App组件定义import React from 'react'import Child from './components/Child'export default function App() {const ChildRef: any = React.useRef(null)const change = () => {console.log(ChildRef) // {current: null}}return (<div><button onClick={change}> click </button><Child ref={ChildRef} /></div>);}
此时触发App组件中button的事件打印current为null得知,上述代码已经实现ref不能绑定函数组件的问题,但是并没有访问到Child组件,我们需要使用Hook useImperativeHandle
useImperativeHandle
// 在Chile组件中添加如下代码function Child(props: any, ref: any) {React.useImperativeHandle(ref, () => {return {Fn// 需要传什么,也可以是状态title// return带返回值就是ref获得到到内容}})......}export default forwardRef(Child)
此时上述说的 ChileRef = { current: {Fn: ƒ} }
useReducer
用于定义状态,修改状态,与useState相似
