单击按钮后在滑块中反应更改幻灯片

react change slide in slider after clicking a button

我有一个以这种方式实现的边栏:

import React from "react";
import './MySidebar.scss';
import {slide as Menu } from 'react-burger-menu'

export class MySidebar extends React.Component {


  constructor(props) {
    super(props);
  }


 changeSlide = (e) => {
   console.log("Clicked " + e.currentTarget.id); //get text content of
 }


  render() {


    return (
        <Menu customCrossIcon={false}>
            <button onClick={((e) => this.changeSlide(e))} className ="menu-item" id="Project1">Project 1</button>
      <button onClick={((e) => this.changeSlide(e))} className ="menu-item" id="Project2">Project 2</button>
        </Menu>
    );
  }
} 

然后我有一个组件叫做ProjectSliderComponent,它实现了轮播的行为。它是这样完成的:

import React from "react";
import Slider from "react-slick";
import './project-carousel.component.css';
import { ProjectComponent } from '../project/project.component';
import { LoggerService } from '../../services/logger-service';
import { appConfig } from '../../config';

export class ProjectSliderComponent extends React.Component {

  state = {
    activeSlide: 0,
    timestamp: Date.now()
  }

  constructor(props) {
    super(props);
    this.logger = new LoggerService();

    this.settings = {
      dots: appConfig.dots,
      arrows: false,
      adaptiveHeight: true,
      infinite: appConfig.infinite,
      speed: appConfig.speed,
      autoplay: appConfig.autoplay,
      autoplaySpeed: appConfig.autoplaySpeed,
      slidesToShow: 1,
      slidesToScroll: 1,
      mobileFirst: true,
      className: 'heliosSlide',
      beforeChange: (current, next) => {
        this.setState({ activeSlide: next, timestamp: Date.now() }); 
      }
    };
  }

  render() {

    let i = 0;

    return (
      <div>
      <Slider ref = {c => (this.slider = c)} {...this.settings}>
        {
          this.props.projectListId.data.map(projectId =>
              <ProjectComponent key={projectId} id={projectId} time={this.state.timestamp} originalIndex={ i++ } currentIndex = {this.state.activeSlide}></ProjectComponent>)
        }
      </Slider>
      </div>
    );
  }
}

ProjectComponent 组件仅指定布局。这是 App.js 文件,我在其中加载项目滑块组件和侧边栏。我这样做:

class App extends Component {

  state = {
    projectList: new ProjectListModel(),
    isLoading: true
  }

  constructor(props) {
    super(props);
    this.logger = new LoggerService();
  }



  componentDidMount() {
    let projectService = new ProjectService();
    projectService.getProjectList()
      .then(res => {
        let projectList = new ProjectListModel();
        projectList.data = res.data.data;
        this.setState({ projectList: projectList,
                        isLoading: false });
      })
      .catch(error => {
        this.logger.error(error);
      });
  }



  render() {
      return (
        <div className="App">
          <MySidebar>
            </MySidebar>
          <ProjectSliderComponent projectListId={this.state.projectList}></ProjectSliderComponent>
        </div>
      );
    }
}

export default App;

我需要做的是根据我点击的按钮来改变幻灯片。我需要做什么?是否有类似传递 projectslidercomponent 的 "instance" 并调用方法来更改幻灯片的方法?或者别的什么?

在 react-slick 文档中,您可以阅读有关 slickGoTo 的内容,这是 Slider 组件的一种方法。

由于您已经存储了 this.slider,您可以尝试在 MySidebar 中访问它并在调用 changeSlide 时使用它。您很可能必须在顶层创建一个 changeSlide 方法并将其作为 属性 传递给您的组件。

要解决这个问题,您需要做的是在父组件中创建一个函数来更新应用程序组件的状态,一旦状态更新,它将重新渲染应用程序组件并将新道具发送到滑块组件这将告诉显示哪个滑块。下面是代码:-

在App.js

class App extends Component {

  state = {
    projectList: new ProjectListModel(),
    isLoading: true,
    menuId: 0
  }

  constructor(props) {
    super(props);
    this.logger = new LoggerService();
  }



  componentDidMount() {
    let projectService = new ProjectService();
    projectService.getProjectList()
      .then(res => {
        let projectList = new ProjectListModel();
        projectList.data = res.data.data;
        this.setState({ projectList: projectList,
                        isLoading: false });
      })
      .catch(error => {
        this.logger.error(error);
      });
  }

  ChangeSlide = (menuId) => {
   this.setState({
      menuId //Here you will receive which slide to show and according to that render slides in mySliderbar component
   })
  }



  render() {
      return (
        <div className="App">
          <MySidebar ChangeSlide={this.ChangeSlide} />
          <ProjectSliderComponent menuId={this.state.menuId} projectListId={this.state.projectList}></ProjectSliderComponent>
        </div>
      );
    }
}

export default App;

在我的幻灯片中

import React from "react";
import './MySidebar.scss';
import {slide as Menu } from 'react-burger-menu'

export class MySidebar extends React.Component {


  constructor(props) {
    super(props);
  }


 changeSlide = (e) => {
   console.log("Clicked " + e.currentTarget.id); //get text content of
   this.props.changeSlide(e.currentTarget.id)
 }


  render() {


    return (
        <Menu customCrossIcon={false}>
            <button onClick={((e) => this.changeSlide(e))} className ="menu-item" id="Project1">Project 1</button>
      <button onClick={((e) => this.changeSlide(e))} className ="menu-item" id="Project2">Project 2</button>
        </Menu>
    );
  }
} 

在 slider 组件中,你必须监听新的 props 何时到来,并根据那个改变 slide see componentWillReceiveProps

import React from "react";
import Slider from "react-slick";
import './project-carousel.component.css';
import { ProjectComponent } from '../project/project.component';
import { LoggerService } from '../../services/logger-service';
import { appConfig } from '../../config';

export class ProjectSliderComponent extends React.Component {

  state = {
    activeSlide: 0,
    timestamp: Date.now()
  }

  constructor(props) {
    super(props);
    this.logger = new LoggerService();

    this.settings = {
      dots: appConfig.dots,
      arrows: false,
      adaptiveHeight: true,
      infinite: appConfig.infinite,
      speed: appConfig.speed,
      autoplay: appConfig.autoplay,
      autoplaySpeed: appConfig.autoplaySpeed,
      slidesToShow: 1,
      slidesToScroll: 1,
      mobileFirst: true,
      className: 'heliosSlide',
      beforeChange: (current, next) => {
        this.setState({ activeSlide: next, timestamp: Date.now() }); 
      }
    };
  }
  componentWillReceiveProps(nextProps) {
   if(nextprops.menuId != this.props.menuId){
    this.slider.slickGoTo(nextprops.menuId, true)//use slider instance to 
    //call the function to go to a particular slide.
   }
  }


  render() {

    let i = 0;
    const { menuId } = this.props
    return (
      <div>
      <Slider initialSlide={menuId} ref = {c => (this.slider = c)} {...this.settings}>
        {
          this.props.projectListId.data.map(projectId =>
              <ProjectComponent key={projectId} id={projectId} time={this.state.timestamp} originalIndex={ i++ } currentIndex = {this.state.activeSlide}></ProjectComponent>)
        }
      </Slider>
      </div>
    );
  }
}