javascript - ReactJs中Antd Carousel上的TSLint错误“属性'carousel'不存在”
问题描述
我在 React & TypeScript 中使用 Ant Design Carousel 组件。Carousel 组件上有“next”和“prev”方法。
代码运行,但是 TSLint 突出显示“carousel”并抛出此错误“Property 'carousel' does not exist on type 'StyledCarousel'.ts(2339)”。我缺少一些打字声明吗?
蚂蚁设计文档在这里
import React from 'react';
import { Carousel, Icon } from 'antd';
class StyledCarousel extends React.Component {
constructor(props: any) {
super(props);
this.state = {};
this.next = this.next.bind(this);
this.previous = this.previous.bind(this);
this.carousel = React.createRef();
}
public next = () => {
this.carousel.next();
};
public previous = () => {
this.carousel.prev();
};
public render() {
const props = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
};
return (
<div>
<Icon type="left-circle" onClick={this.previous} />
<Carousel ref={node => (this.carousel = node)} {...props}>
<h1>Item 1</h1>
<h1>Item 2</h1>
<h1>Item 3</h1>
</Carousel>
<Icon type="right-circle" onClick={this.next} />
</div>
);
}
}
export default StyledCarousel;
解决方案
您没有carousel
在组件中为字段定义类型,因此 TSLint 不知道它,也不知道分配给它的对象的方法。您应该像这样在类中定义它:
private carousel: React.RefObject<Carousel>;
另一方面,您还应该考虑使用新语法在 React 组件中创建 refs 并refField.current
用于访问被引用的组件。
最后你的组件应该是这样的:
import React from 'react';
import { Carousel, Icon } from 'antd';
class StyledCarousel extends React.Component {
private carousel: React.RefObject<Carousel>;
constructor(props: any) {
super(props);
this.next = this.next.bind(this);
this.previous = this.previous.bind(this);
this.carousel = React.createRef();
}
public next = () => {
if (this.carousel.current)
this.carousel.current.next();
};
public previous = () => {
if (this.carousel.current)
this.carousel.current.prev();
};
public render() {
const props = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
};
return (
<div>
<Icon type="left-circle" onClick={this.previous} />
<Carousel ref={this.carousel} {...props}>
<h1>Item 1</h1>
<h1>Item 2</h1>
<h1>Item 3</h1>
</Carousel>
<Icon type="right-circle" onClick={this.next} />
</div>
);
}
}
export default StyledCarousel;
推荐阅读
- java - 如何使用 EventHandler 在舞台上加载图像
? - javascript - 文档对象模型 (DOM) 中的对象是什么意思
- python - 使用数组的三个随机元素的中位数作为枢轴实现快速排序
- windows - 如何为 WSL(Linux 的 Windows 子系统)安装 GCC 和 GDB?
- python - 如何在 Python 3 中使用 cmd
- angularjs - 连接到 Angular Docker 容器时出错
- javascript - 如何在 Node.js 中创建 NTLM 令牌?
- mysql - 在使用 JSON_EXTRACT 的 SQL 语句上使用多个 HAVING 子句
- html - 为什么这个文本应该浮动到右边,但它会浮动到左边?
- android - 如何根据android中该视图的坐标知道一个视图何时位于另一个视图之上