使用 Hook 访问组件方法



我正在尝试按照此文档轮播制作一个简单的轮播 轮播

工作示例

我如何翻译上面的功能组件/钩子。

我一直在尝试在点击按钮中绑定 next((,但我似乎无法让它工作。如何正确访问下一个方法并将其绑定到我的按钮中?

<Carousel ref={c => (this.slider = c)} >
<div>
<h3><Button onClick={() => this.carousel.next()}>1</Button></h3>
</div>
<div>
<h3><Button onClick={() => this.carousel.prev()}>2</Button></h3>
</div>
<div>
<h3>3</h3>
</div>
<div>
<h3>4</h3>
</div>
</Carousel>

您可以从<Carousel />ref访问next()api。使用函数组件,您可以使用useRef钩子,如下所示:

import React, { useRef } from "react";
import { Carousel } from "antd";
export function App() {
const carousel = useRef(null);
function next() {
carousel.current.next();
}
return (
<div>
<Carousel ref={carousel}>
<div>
<h3>1</h3>
</div>
<div>
<h3>2</h3>
</div>
<div>
<h3>3</h3>
</div>
<div>
<h3>4</h3>
</div>
</Carousel>
<button onClick={next}>Next</button>
</div>
);
}

https://codesandbox.io/s/carousel-react-ref-hook-next-492gv

最新更新