JavaScript/react/React.forwardRef

来自康健生活
Kangkk​(留言 | 贡献)2021年3月10日 (三) 03:29的版本 (→实践一)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

引言

引用传递(Ref forwading)是一种通过组件向子组件自动传递 引用ref 的技术。

示例

const  A=React.forwardRef((props,ref)=>(
  <div ref={ref}>
    <B {...props} />
  </div>
))
Warning: React.forwardRef 的 API 中 ref 必须指向 dom 元素而不是 React 组件

实践

实践一

在一个需求中,我是用了自定义的 modal.FC 在 react.FC 中调用这个方法渲染一个弹出框,因为是函数调用,在 return 之前,所以不能绑定到弹出框中的 input 的 ref,也就获取不到 input 的 value 值。

这个时候可以使用 forwardRef 进行引用传递。

import React, { useState, useLayoutEffect, useContext, useEffect, useRef, forwardRef } from 'react';
...
const FocusInput = forwardRef((props, ref) => (
      <Input ref={ref} {...props}/>
  ));
  const createTeamNameInputRef = useRef();

  const handlerCreateTeamConfirm = (e)=>{
    console.log('createTeamNameInput', createTeamNameInputRef.current.value)
...
  }
  const handlerCreateTeamCancel = (e)=>{
    teamModal.destroy()
  }
  const newHandler = [
    {
      key: 'team',
      label: '新建团队',
      icon: 'supervisor_account',
      access: 'VIEWER',
      // async action() {
      async action() {
        teamModal = Modal.FC({
          box: [440,240],
          visible: true,
          padding: "25px 30px",
          header: <><p className="modal-create__team--header">新建团队</p><p className="modal-create__team--header-sub">组件团队</p></>,
          children: <><FocusInput ref={createTeamNameInputRef} type="text" className="input-create__team--name" placeholder="请输入团队名称" /></>,
          footer: [
            {domType: 'button', styleType: 'link', children: '取消', onClick: handlerCreateTeamCancel},
            {domType: 'button', styleType: 'primary', children: '确定', box: [80, 32], onClick: handlerCreateTeamConfirm}
          ],
          footerAlign: 'right'
        })
...