首页 > 解决方案 > 如何在打字稿中构建函数回调?

问题描述

我正在尝试在 typescript 中执行回调函数,并且教程解释说我们必须使用 ref 执行此操作。我成功在引用(组件主页)中使用 scrollIntoView ,但是当我尝试以相同的方式为回调函数创建 ref 时,它不起作用......

我收到了这个错误:

TypeError: routerRef.current.scrollToSection is not a function

我试过没有电流,但这是同样的问题:

TypeError: routerRef.scrollToSection is not a function

请问你能帮帮我吗 ?

我的标题组件:

const Header = () => {


    const routerRef :any = useRef(React.createRef());

    function scrollToSection(section : number){
        routerRef.scrollToSection(section);
    }



    return (
        ...
                        <li className="navbar_item_title" onClick={() => scrollToSection(1)}>{text[language].home} </li>
                        <li className="navbar_item_title" onClick={() => scrollToSection(2)}>{text[language].my_portrait} </li>
                        <li className="navbar_item_title" onClick={() => scrollToSection(3)}>{text[language].contact}</li>
...
            <Router ref={routerRef} updateNavBarDisplay={updateNavBarDisplay}></Router>
    );
}
export default Header;

我的路由器组件:

interface Props {
    ref: any
}
const Router = () => {

    const homeRef :any = useRef(React.createRef());

    function scrollToSection(section : number){
        homeRef.scrollToSection(section);
    }

    return (
        <BrowserRouter>
            <Switch>
                <Route exact path="/" render={() => <Home ref={homeRef} updateNavBarDisplay={updateNavBarDisplay} />} />
                <Route path="*" component={NotFound} />
            </Switch>
        </BrowserRouter>
    );
}
export default Router;

我的家庭组件:

const Home = () => {

    const sectionRef1: any = useRef(React.createRef());
    const sectionRef2: any = useRef(React.createRef());

    const scroll = (ref: any) => {
        ref.current.scrollIntoView({
            behavior: 'smooth',
            block: 'start',
        });
    };

    function scrollToSection(section: number) {
        if (section === 1) {
            scroll(sectionRef1);
        }
        else if (section === 2) {
            scroll(sectionRef2);
        }
        else if (section === 3) {
            //TODO: active button
        }
    }
    return (
        <div>
            <div ref={sectionRef1} />
            <VisibilitySensor partialVisibility={true} onChange={onChange}>
                <Carrousel></Carrousel>
            </VisibilitySensor>
            <div ref={sectionRef2} />
            <Portrait></Portrait>

        </div>
    );
}
export default Home;

为了更清楚,我删除了部分代码。

我希望你能告诉我什么是错的,提前谢谢!

标签: reactjstypescript

解决方案


推荐阅读