使用Hooks访问组件方法

时间:2019-08-08 09:23:39

标签: reactjs react-hooks antd

我正在按照本文档Carousel

制作一个简单的轮播

工作example

如何在上面翻译以使用功能组件/挂钩。

我一直试图在onClick Button中绑定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>

1 个答案:

答案 0 :(得分:2)

您可以从<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