【问题标题】:Define callback ref TypeScript and react-slick library定义回调参考 TypeScript 和 react-slick 库
【发布时间】:2021-04-27 19:41:54
【问题描述】:

我正在使用 TypeScript 构建一个 React 应用程序。我正在使用 React-Slick 的轮播。

我正在尝试以编程方式更改轮播的幻灯片。因此我关注the documentation 并尝试为 Slider 创建一个引用。我的组件是这样的:

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

当我像这样在我的组件中定义回调 ref 时,出现一个错误: “'Section' 类型上不存在属性 'setRef'”。如何在 TypeScript 中为 react-slick 库定义回调引用?

【问题讨论】:

    标签: reactjs typescript react-slick


    【解决方案1】:

    要向 typescript 类添加属性,您需要在类的主体中定义它们的类型。

    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;
        };
    }
    

    【讨论】:

    • 感谢您的回答,但我添加的那两行有一个错误'Slider' refers to a value, but is being used as a type here. Did you mean 'typeof Slider'?
    • 错误信息提出的解决方案对我来说似乎是正确的。
    • 如果这不起作用,也许这个 Slider 组件暴露了一个与它自己不同的对象作为它的引用。如果您在 VSCode 中,您可以将鼠标悬停在 ref={this.setRef} 中的 ref 上,它会告诉您它正在处理的类型,然后您可以将该类型复制到您的中
    • 我正在使用 Sublime,但我不知道它的帽子类型。
    • 我将其更改为“任何”并且它可以工作,但我怎么知道它是什么类型?无论如何我接受你的回答。
    猜你喜欢
    • 2020-08-14
    • 1970-01-01
    • 2018-09-03
    • 2012-10-19
    • 2018-03-23
    • 2014-11-13
    • 2016-01-01
    • 2013-02-13
    • 2017-05-14
    相关资源
    最近更新 更多