React调用子组件方法和数据:class组件 | function组件

Class组件可以通过配置ref,父组件就可以调用到子组件的function和data

父组件

import { FC, useState, useEffect, useRef } from 'react';

const IndexPage: FC = () => {
  const classListRef = useRef();
  
  return (
    <>
      <Button 
        onClick={(dim) => {
          classListRef?.current?.queryList({
            id: dim.id,
          });
        }}
      </Button>
      <MyClassList ref={classListRef} />
    </>
  )
}

Class子组件

class MyClassList extends React.PureComponent<ListProps,ListState> {
  queryList = (params?) => {
    ....
  }
  
  render() {
    return (
      <>
        ....
      </>
    )
  }
}
export default MyClassList;

function子组件不能直接使用ref

  • 需要React.forwardRef()包一层
  • 通过useImperativeHandle(props.listRef, () => ({ ... })配置暴露给父组件的function和data

父组件

import { FC, useState, useEffect, useRef } from 'react';

const IndexPage: FC = () => {
  const hookListRef = useRef();
  
  return (
    <>
      <Button 
        onClick={() => {
          hookListRef.current?.cancelSelectedDimension();
        }}
      </Button>
      <MyHookList ref={hookListRef} />
    </>
  )
}

子组件

import React, { FC, useImperativeHandle } from 'react';
type ItemDataType = {
  id: number;
  name?: string;
  // 更多属性...
}
const MyHookList: FC<ListProps> = (props) => {
  useImperativeHandle(props.listRef, () => ({
    // 暴露给父组件的data
    selectedDimension: selectValue,
    // 暴露给父组件的方法
    cancelSelectedDimension: () => { 
      setSelectValue(undefined)
    }
  }));
  
  const [selectValue, setSelectValue] = useState<ItemDataType>();
  
  return (
    <>
      ....
    </>
  )
}

export default React.forwardRef((props: ListProps, ref?: any) => {
  return <MyHookList {...props} listRef={ref} />;
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容