如何使用函数组件向 ref 公开函数?

mah*_*zad 13 reactjs react-native

我想创建一个组件可以说,这可能会暴露一些类似功能的日历功能组件nextMonthprevMonth因此使用它可以访问这些功能的父组件使用,等等ref。使用类组件很容易,因为实例方法是自动公开的。如何使用功能组件实现相同的功能?我知道我可以为此使用渲染道具模式。但是还有其他解决方案吗?

粗略的例子:

function Calendar() {
   const nextMonth = () => {...}
   const prevMonth = () => {...}

   return (
      <div>.....</div>
   )
}


function Parent() {
   const cal = createRef();

   const onNext = () => {
     cal.current.nextMonth();
   }

   return (
     <>
        <Calendar ref={cal} />
        <button onClick={onNext}>Next</button>
     </>
   )
}

Run Code Online (Sandbox Code Playgroud)

Ham*_*mid 17

您可以使用useImperativeHandle钩子。

const Calendar = React.forwardRef((props, ref) => {
  const [month, setMonth] = useState(0)
  const nextMonth = () => { setMonth((prev) => prev + 1) }
  const prevMonth = () => { setMonth((prev) => prev - 1) }

  useImperativeHandle(ref, () => ({
    nextMonth,
    prevMonth
  }));

  return (
    <div>{month}</div>
  )
})

const Parent = () => {
  const cal = useRef()

  const onNext = () => {
    cal.current.nextMonth()
  }

  return (
    <React.Fragment>
      <Calendar ref={cal} />
      <button type="button" onClick={onNext}>Next</button>
    </React.Fragment>
  )
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*eer 5

这是你可以做到的方法,即使它不是真正的 React 方式。诀窍是设置refin的当前值Calendar

const Calendar = React.forwardRef((props, ref) => {
  const [month, setMonth] = useState(0)
  const nextMonth = () => { setMonth((prev) => prev + 1) }
  const prevMonth = () => { setMonth((prev) => prev - 1) }

  ref.current = { nextMonth, prevMonth } // eslint-disable-line

  return (
    <div>{month}</div>
  )
})

const Parent = () => {
  const cal = useRef()

  const onNext = () => {
    cal.current.nextMonth()
  }

  return (
    <React.Fragment>
      <Calendar ref={cal} />
      <button type="button" onClick={onNext}>Next</button>
    </React.Fragment>
  )
}
Run Code Online (Sandbox Code Playgroud)