【React Hook】之useImerpativeHandler

作用:将函数内的方法返回给ref绑定的组件

类组件写法:利用ref, 在父组件中调用子组件事件

这个Hook的第三个参数是一个[], 这个[]中的数据决定了这个Hook会再次执行

Hello.js

import React, {Component} from 'react'

export default class Hello extends Component {
    handler = () => {
        alert('Hello world')
    }

    render() {
        return (
            <div>Hello</div>
        )
    }
}

App.js

import Hello from "./components/Hello";
import React from "react";

export default class App extends React.Component {
    fn= () => {
        this.hello.handler()
    }
    render() {
        return (
            <div>
                <button type = "primary" onClick = {this.fn}>click</button>
                <Hello ref = {el => this.hello = el}></Hello>
            </div>
        )
    }
}

函数组件写法:

利用useImperativeHandler

Hello.js

import React, {Component, forwardRef,useState, useImperativeHandle} from 'react'

export default forwardRef(function Hello(props, ref) {
  const [n, setN] = useState(0)
  // 定义方法
  useImperativeHandle(ref, () => {
      // 这里定义让父组件执行的方法
      return {
          add() {
              setN(n=> n + 1)
          }
      }
  }, []) // 第三个参数, n的改变会影响回调函数的执行
  return (
      <div>Hello内部的{n}</div>
  )
})

 App.js

import Hello from "./components/Hello";
import React, {useRef} from "react";

export default function App() {
    const hello = useRef(null)
    const handler = () => {
        // 拿到hello内部的方法
        console.log("hello", hello)
        hello.current.add()
    }
    return (
        <div>
            <button onClick = {handler}>触发hello组件中的方法</button>
            <Hello ref = {hello}/>
        </div>
    )
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值