react-slick slickNext 方法 - “未捕获的类型错误:无法读取未定义的属性‘滑块’”

Posted

技术标签:

【中文标题】react-slick slickNext 方法 - “未捕获的类型错误:无法读取未定义的属性‘滑块’”【英文标题】:react-slick slickNext method - "Uncaught TypeError: Cannot read property 'slider' of undefined" 【发布时间】:2017-01-09 02:21:27 【问题描述】:

我正在使用带有 Green Sock 动画工具的 react-slick 轮播,并且我已经让滑块和动画工作了。现在的问题是当动画在幻灯片上结束时调用 slickNext 方法。无论我是否使用 refs,我都会不断收到此错误(但我的“测试”正在运行并显示在控制台中)。这种方法的 github 文档有点贫乏和混乱,我还没有发现任何类似的情况可以作为参考。如何访问此方法?

import React,  Component  from "react";
import Helmet from "react-helmet";
import AnimationStory1 from "../../components/Animation/AnimationStory1";
import AnimationStory2 from "../../components/Animation/AnimationStory2";
import AnimationStory3 from "../../components/Animation/AnimationStory3";
var Slider = require("react-slick");

export default class IntroStory extends Component 

  constructor (props) 
    super(props);
    this.state = ;
  

  nextSlide () 
    console.log("test");
    this.refs.slider.slickNext();
  

  render () 
//These are GreenSock animation instances
    var timeline1 = new TimelineLite(onComplete: this.nextSlide);
    var timeline2 = new TimelineLite();
    var timeline3 = new TimelineLite();

//These are settings for the react-slick slider
    var settings = 
      dots: true,
      infinite: true,
      speed: 500,
      slidesToShow: 1,
      slidesToScroll: 1,
//      slide: true,
      swipe: true,
      accessibility: true,
      arrows: false,
      beforeChange: function () 
        timeline1.restart();
        timeline2.restart();
        timeline3.restart();
      
    ;

    return <div>
      <Helmet title="Welcome to We Vote" />
      <div className="container-fluid well u-gutter__top--small fluff-full1 intro-story">
        <Slider ref="slider" ...settings>
          <div key=1><AnimationStory1 timeline1=timeline1/></div>
          <div key=2><AnimationStory2 timeline2=timeline2/></div>
          <div key=3><AnimationStory3 timeline3=timeline3/></div>
          <div key=4><p>This will be an image</p></div>
         </Slider>
      </div>
    </div>;
  

【问题讨论】:

【参考方案1】:

绑定您的方法以确保处理上下文this

 render () 
//These are GreenSock animation instances
    var timeline1 = new TimelineLite(onComplete: this.nextSlide.bind(this));
    var timeline2 = new TimelineLite();
    var timeline3 = new TimelineLite();

当你刚刚通过时, var timeline1 = new TimelineLite(onComplete: this.nextSlide) 您实际上只是专注于传递回调,但是方法 nextSlide 使用 this 上下文,并且在调用回调时,您需要确保 this 在其中包含 refs 以调用 slider . Read more here

【讨论】:

以上是关于react-slick slickNext 方法 - “未捕获的类型错误:无法读取未定义的属性‘滑块’”的主要内容,如果未能解决你的问题,请参考以下文章

react-slick 没有滑动效果

如何在另一个 index.js 文件上导出 react-slick?

`react-slick` - 类型无效错误

无法从“react-slick”解析“SimpleSlider.js”

React-slick 与 gatsby-plugin-image

维护多个 react-slick 的索引