首页 > 其他分享 >react ref和context

react ref和context

时间:2024-04-08 22:16:00浏览次数:14  
标签:React value react context 组件 import ref

ref获取dom context类似provider和injected,用于嵌套很深的爷孙组件传值 子组件使用父组件创建的context对象,不能自己创建 context创建在函数组件和class组件都是一样的

export let Context1 = React.createContext('')
<Context1.Provider value='Context value 函数组件'>
        <FSon></FSon>
      </Context1.Provider>

 

 

函数组件

1.使用useRef hook来获取ref 2.ref不能获取函数组件, 但能获取普通dom
  let dom1 = useRef<HTMLHeadingElement>(null)
  useEffect(() => {
    console.log(dom1.current)
  }, [])
<h3 ref={dom1}>函数组件</h3>

 

3.Context 只能有value这个props 4.使用useContext hook来获取useContext 
import { Context1 } from '../index'
let value = useContext(Context1)

 

class组件

1.ref必须挂载完成后才能获取,在componentDidMount 2.ref通过React.createRef()方法获取
div1 = React.createRef<HTMLHeadingElement>()
<h3 ref={this.div1}>class组件</h3>
3.context通过context.Consumer去接受
 import { Context1 } from '../index'
 {/* 接收信息 */}
        <Context1.Consumer>{
          (value) => { return <div>{value}</div> }
        }</Context1.Consumer>

 

 
import styles from './index.less';
import { Button } from 'antd';
import React, { useEffect, useRef } from 'react';
import Son from './components/son'
import FSon from './components/fSon'
export let Context1 = React.createContext('')
const HomePage: React.FC = () => {
  class Cc extends React.Component {
    div1 = React.createRef<HTMLHeadingElement>()
    sonCom = React.createRef<HTMLHeadingElement>()
    state = {
      passMes: "我是一个传递的消息 class组件"
    }
    componentDidMount() {
      console.log(this.div1.current)
      console.log(this.sonCom.current)
      // this.sonCom.current.f1()
    }
    render() {
      return <div>
        <h3 ref={this.div1}>
          class组件
        </h3>
        <div>ref必须挂载完成后才能获取,在componentDidMount</div>
        {/* 只能有value这个props */}
        {/* 传递信息 */}
        <Context1.Provider value={this.state.passMes}>
          <Son ref={this.sonCom}></Son>
        </Context1.Provider>
      </div>
    }
  }
  let dom1 = useRef<HTMLHeadingElement>(null)
  useEffect(() => {
    console.log(dom1.current)
  }, [])
  return (
    <div className={styles.container}>
      <h2>ref和context</h2>
      <div>context类似provider和injected,用于嵌套很深的爷孙组件传值</div>
      <div>子组件使用父组件创建的context对象,不能自己创建</div>
      <h3 ref={dom1}>函数组件</h3>
      <div>ref不能获取函数组件</div>
      <Context1.Provider value='Context value 函数组件'>
        <FSon></FSon>
      </Context1.Provider>
      <Cc></Cc>
    </div>
  );
};



export default HomePage;
import { useContext } from 'react';
import { Context1 } from '../index'
const Son: React.FC = () => {
  let value = useContext(Context1)
  return <div>
    <div>{value}</div>
  </div>
};
export default Son;
import React from 'react'
import { Context1 } from '../index'
class GrandSon extends React.PureComponent {
  state = {
    msg: 'grandSon'
  }
  f1() {
    console.log(1)
  }
  render() {
    return (
      <div>
        <div>{this.state.msg}</div>
        {/* 接收信息 */}
        <Context1.Consumer>{
          (value) => { return <div>{value}</div> }
        }</Context1.Consumer>
      </div>

    )
  }
}
// export default Son;
const ForwardedGrandSon = React.forwardRef<HTMLDivElement>((props, ref) => {
  return <GrandSon ref={ref as React.RefObject<GrandSon>} {...props} />;
});
export default ForwardedGrandSon;

 

标签:React,value,react,context,组件,import,ref
From: https://www.cnblogs.com/ssszjh/p/18122747

相关文章

  • react 函数组件和hook
    函数组件1.函数组件没有生命周期2.函数组件没有this3.函数组件通过hook完成各种操作4.函数组件本身就是render函数5.props在函数第一个参数解释useState参考https://www.cnblogs.com/ssszjh/p/14581014.htmlprops参考https://www.cnblogs.com/ssszjh/p/18118746生命周期......
  • react 性能问题和优化
    某个组件更新,子组件也会一起更新react更新采用时间切片,vue则是依赖收集执行更新操作为16ms,如果操过16ms,先暂停更新,让浏览器先渲染时间切片时间是16ms,因为人眼刷新率约60帧,60hz为16ms1.避免state改为同样的值(class用PureComponent,函数组件默认已经处理了)2.处理子组......
  • react 生命周期
    1.class组件初次挂载1.constructor2.getDerivedStateFromProps3.render4.componentDidMount 更新数据1.getDerivedStateFromProps2.shouldComponentUpdate3.render4.componentDidUpdate备注:1.PureComponent里不能写shouldComponentUpdate2.优化性能一般在shoul......
  • react中redux基本使用二
    1.action传参,用payload属性接收  <buttononClick={()=>dispatch(addNum(2))}>+2</button> 2.redux中异步操作,与同步类似,需要比同步多封装一个函数//使用RTK创建store,createSlice创建reducer的切片//使用RTK创建store,createSlice创建reducer的切片import......
  • react中redux基本使用
    1.安装 npminstall@reduxjs/toolkitreact-redux2.创建store目录 3.创建counterStore.js//使用RTK创建store,createSlice创建reducer的切片import{createSlice}from"@reduxjs/toolkit";constcounterSlice=createSlice({//需要一个配置对象作为参数,通过......
  • [React] Using key prop to reset component to avoid useEffect hook
    ThecomponentusinguseEffectwhichisnotnecessary:functionTopicEditor({selectedTopicId}){const[enteredNote,setEnteredNote]=useState('');constselectedTopic=DUMMY_TOPICS.find(topic=>topic.id===selectedTopicId)......
  • go reflect
    goreflect反射核心反射的核心是两个对象,分别是reflect.Type和reflect.Value。它们分别代表了go语言中的类型和值。我们可以通过reflect.TypeOf和reflect.ValueOf来获取到一个变量的类型和值。funcmain(){ vara=1 fmt.Println(reflect.ValueOf(a)) fmt.Print......
  • 全栈的自我修养 ———— react路由两种传参方法
    react路由传参1、传统传参跳转前:跳转后:结果:2、配置传参跳转前:配置routes:跳转后:结果:1、传统传参跳转前:import{useNavigate}from"react-router-dom";<divclassName='login'onClick={()=>navigator('/public/login?id=1')}> <div......
  • 全栈的自我修养 ———— react router6默认二级路由配置?嵌套时候如何实现默认导航
    在组件嵌套时候小编定义了一个共同组件于/public地址下,小编发现如果直接访问public是只有外部组件的页面,小编目标是访问public时候直接访问index页面,小编找了很多资料最终自己使出来了一个办法如下!!小编自己发现的后来查找到的小编自己发现的即把{pat......
  • 全栈的自我修养 ———— react未知地址默认导航至404页面
    方法1在根目录上添加一个errorElement{path:'/',element:<Navigateto="/public/index"replace/>,errorElement:<div>errorPage</div>},方法2{path:'*',element:<div>errorPage</di......