JavaScript/react/React.forwardRef:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
 
(未显示同一用户的2个中间版本)
第11行: 第11行:


{{Warning|React.forwardRef 的 API 中 ref 必须指向 dom 元素而不是 React 组件}}
{{Warning|React.forwardRef 的 API 中 ref 必须指向 dom 元素而不是 React 组件}}
== 实践 ==
=== 实践一 ===
在一个需求中,我是用了自定义的 modal.FC 在 react.FC 中调用这个方法渲染一个弹出框,因为是函数调用,在 return 之前,所以不能绑定到弹出框中的 input 的 ref,也就获取不到 input 的 value 值。
这个时候可以使用 forwardRef 进行引用传递。
<syntaxhighlight lang="javascript">
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'
        })
...
</syntaxhighlight>