我想创建一个组件,比如一个日历功能组件,它可以公开一些功能,比如nextMonthprevMonth等,这样使用它的父组件就可以使用ref访问这些功能.使用类组件很容易,因为实例方法会自动公开.如何使用功能组件实现同样的功能?我知道我可以使用渲染props 模式.但还有其他解决办法吗?

粗略的例子:

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>
     </>
   )
}

推荐答案

你可以用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>
  )
}

React-native相关问答推荐

Appcenter codepush 返回请求被阻止

将 Cognito 用户与真实数据库用户联系起来的最佳方式是什么?

RTK 查询显示互联网何时关闭?

如何在 React Navigation 5 中将父函数传递给子屏幕?

react-native 签名 [AppName]Tests 需要开发团队 ios

TextInput 防止 ScrollView 滚动

如何使用 AND/OR 运算符过滤列表/查询 AWS Amplify JavaScript GraphQL

React Native - ScrollView 中的 ListView 分页?

如何实时从 react-native-camera 获取帧

React Native:双击退出应用程序

React-Native:显示加载屏幕直到加载 webview

错误:安装 react-native-elements 后无法识别字体系列 Material Design 图标?

如何在 React-Native 的alert中设置alert框标题?

require() 必须有一个字符串文字参数 React Native

React-native:图像未显示在 android 设备中,但在模拟器中完美显示

xcode 10错误:multiple commands produce

Super expression must either be null or a function, not undefined

运行 expo start 时如何禁用在浏览器中打开 DevTools?

xcode 使用错误的 node.js 版本

React Native 的最佳文件 Select 器