求大佬指点一个ts简单的react的ref提示报错

嘻倪孢
  • 330

我就只想ts提示我暴露的getData 方法

import React, { Component, useRef } from 'react';
type childRef = {
  getData: () => []
}

function Parent () {
  const childref = useRef<childRef|null>(null)
    // 这里这个ref标红
  return <Child ref={childref}/>
}

type IChild = {
  ref:childRef
}
class Child extends Component<IChild> {
  getData = () => {
    return []
  }
  render() {
    return <div>Child</div>
  }
}

回复
阅读 617
3 个回答
✓ 已被采纳

好像没有写的那么复杂呀,。。我就这样就能识别getData了。。

import React, {Component, useEffect, useRef} from 'react';


function Parent() {
  const childRef = useRef<Child>()
  useEffect(() => {
    childRef.current.getData()
  }, [])
  return <Child ref={childRef}/>
}

class Child extends Component {
  getData = () => {
    return []
  }

  render() {
    return <div>Child</div>
  }
}

补充根据题主需求更新的代码

import React, {Component, useEffect, useRef} from 'react';

interface childRef {
  getData: () => any[];
}

function Parent() {
  const childRef = useRef<Child>()
  useEffect(() => {
    // 在该定义域 as 想要的类型
    const that = childRef.current as childRef;
    that.getData();
  }, [])
  // 如果对childRef进行类型装换 又只想要getData方法。就不符合react对类型的要求了。
  return <Child ref={childRef}/>
}

class Child extends Component {
  getData = () => {
    return []
  }

  render() {
    return <div>Child</div>
  }
}
import React, { Component, useRef } from 'react';

class Child extends Component {
    getData = () => {
        return [];
    };
    render() {
        return <div>Child</div>;
    }
}

function Parent() {
    const childref = useRef<Child>(null);
    useEffect(() => {
        childref.current?.getData();
    }, []);
    return <Child ref={childref} />;
}

组件需要包装一下

import React, { Component, useRef } from 'react';
type childRef = {
  getData: () => [];
};

function Parent() {
  const childref = useRef<childRef | null>(null);
  // 这里这个ref标红
  return <ChildRef ref={childref} />;
}

type IChild = {
  forwardRef: childRef;
};

class Child extends Component<IChild> {
  getData = () => {
    return [];
  };
  render() {
    return <div>Child</div>;
  }
}

const ChildRef = React.forwardRef((props: any, ref: React.ForwardedRef<childRef>) => <Child {...props} forwardRef={ref} />);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏