reactjs - 如何在打字稿中构建函数回调?
问题描述
我正在尝试在 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;
为了更清楚,我删除了部分代码。
我希望你能告诉我什么是错的,提前谢谢!
解决方案
推荐阅读
- adobe - 如何在 AEM Touch UI 对话框中引入具有默认值的附加字段?
- flutter - Flutter 使用过时的包不会让我运行我的应用程序
- jquery - salesforce 使用 jQuery ajax 方法获取令牌
- javascript - 完整日历不是函数 CDN
- r - 计算每个 data.table 行的出现次数
- selenium - 如何将 Azure App 服务连接到 Azure VM?
- java - 如何使方形FrameLayout边框的一侧可拖动以在Android中制作矩形?
- angular - NgRx 访问 State Store 上的数据
- html - 不同的项目变得活跃并被选中,而不是一个项目
- python - 如何从 Pandas DataFrame 中获取用户名