Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
900 views
in Technique[技术] by (71.8m points)

reactjs - Define callback ref TypeScript and react-slick library

I'm building a React app using TypeScript. I'm using React-Slick's carousel.

I'm trying to programmatically change the slide of the carousel. Therefore I followed the documentation and tried to create a ref for the Slider. My component is like this:

import React from 'react';
import Resur from './Resur'
const Slider = require("react-slick").default;

export interface Item {
title: string;
restur: Rest[];
}

export interface Rest {
name: string;
online: boolean;
}

interface AppRefs {
slider: any;
}

class Section extends React.Component<{ item: Item }> {
 private slider: any;

 constructor(props: any) {
    super(props);
    this.slider = null;
    this.setRef = element => {
        this.slider = element;
    };
}
renderArrows() {
  return (
    <div className="slider-arrow">
    <button
      className="arrow-btn prev"
      onClick={() => this.slider.slickPrev()}
    >
        <i className="fa fa-chevron-left"></i>
    </button>

    <button
      className="arrow-btn next"
      onClick={() => this.slider.slickNext()}
    >
        <i className="fa fa-chevron-right"></i>
    </button>
  </div>
);
};
render() {
const settings = {
  infinite: true,
  slidesToShow: 3
};
  var rests = this.props.item.restur.map(function(rest, index) {
    return (
      <Resur rest={rest} key={index} />
    )
  });
return(
  <div>
      <h4 className="section-title text-center">{this.props.item.title}</h4>
      <hr></hr>
      {this.renderArrows()}
      <Slider ref={this.setRef} {...settings}>
        {rests}
      </Slider>
  </div>
  )
 }
}
export default Section

When I defined the callback ref in my component like this, there is an error which says: "Property 'setRef' does not exist on type 'Section'". How can I define my callback ref in TypeScript for react-slick library?

question from:https://stackoverflow.com/questions/65860413/define-callback-ref-typescript-and-react-slick-library

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To add properties to a typescript class, you need to define their types in the body of the class.

class Section extends React.Component<{ item: Item }> {
 private slider: typeof Slider | null; // <---- improved this type
 private setRef: (element: typeof Slider | null) => void; // <---- added this

 constructor(props) {
    super(props);
    this.slider = null;
    this.setRef = element => {
        this.slider = element;
    };
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...