1

我添加react-slick到我的项目中以显示carousel. 我想使用位于滑块内容顶部的自定义下一个和上一个按钮来控制我的滑块。所以我遵循了自定义箭头文档,但我不想在光滑的内容中显示我的按钮,我想将控件提供给滑块内容上方的按钮。如何做到这一点?我从我创建的组件中包含了我的代码。

import React from 'react';
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import Slider from "react-slick";
import { styled } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

function SampleNextArrow(props) {
  const { onClick } = props;
  return (
    <React.Fragment>
      <Button
        onClick={onClick} className="slickRight">
        Next
      </Button>
    </React.Fragment>
  );
}
function SamplePrevArrow(props) {
  const { onClick } = props;
  return (
    <React.Fragment>
      <Button
        onClick={onClick} className="slickLeft">
        Prev
      </Button>
    </React.Fragment>
  );
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {}
  }
  render() {
    var settings = {
      infinite: true,
      speed: 500,
      slidesToShow: 4,
      slidesToScroll: 1,
      nextArrow: <SampleNextArrow />,
      prevArrow: <SamplePrevArrow />,
    };
    return (
      <div>
        {/*Want to Add Control to this Buttons*/
        <Button>Prev</Button>
        <Button>Next</Button>
        
        <div className="container">
          <Slider {...settings}>
            <div>
              <h3>1</h3>
            </div>
            <div>
              <h3>2</h3>
            </div>
            <div>
              <h3>3</h3>
            </div>
          </Slider>
        </div>
      </div>
    );
  }
}

export default App;

4

2 回答 2

1

在这里,您可以通过使用 react useRef Hook 来实现这一点,这是实际的代码:

import React, { useRef } from "react";
import Slider from "react-slick";
 
const SliderComponent = () => {
 const slider = useRef();
  
  const next = () => {
   slider.current.slickNext();
 };
  const previous = () => {
   slider.current.slickPrev();
 }; 
  
  const settings = {
    dots: false,
    infinite: true,
    speed: 500,
    slidesToShow: 2,
    slidesToScroll: 1,
    autoplaySpeed: 3000,
    arrows: false,
  
  responsive: [
   {
    breakpoint: 1024,
    settings: {
      slidesToShow: 2,
      slidesToScroll: 2,
      infinite: true,
      dots: true,
    },
  },
  {
    breakpoint: 768,
    settings: {
      slidesToShow: 1,
      slidesToScroll: 1,
    },
  },
 ],
};
  return(
     <div>
       <button  onClick={previous}> Prev Button </button>
        <Slider ref={(c) => (slider.current = c)} {...settings}>
            <div>Slide 1</div>
            <div>Slide 2</div>
            <div>Slide 3</div>
            <div>Slide 4</div>
            <div>Slide 5</div>
        </Slider>
      <button onClick={next}> Next Button </button>
   </div>            
   )}   
于 2021-06-07T02:28:43.840 回答
0

Nandhini,在使用该软件包之前,您必须完整阅读文档一次。

官方文档https://react-slick.neostack.com/docs/example/previous-next-methods中已经有一个方法

用它。

于 2019-07-13T10:42:25.543 回答