我在悬停在其中一张幻灯片上时尝试使用clearInterval,但它似乎没有做任何事情,我无法弄清楚原因。
不幸的是,我能找到的所有先前的例子都在es5中,我发现那些难以理解
https://www.webpackbin.com/bins/-KmWiawYnD97xCbZYENG
import React from 'react'
import styled from 'styled-components'
import { Link } from 'react-router'
const Bg = styled.div`
width:100px;
height:100px;
background: papayawhip;
`
export default class Hello extends React.Component {
constructor() {
super()
this.state = {
tabId: 1
}
this.handleActive = this.handleActive.bind(this)
this.isShown = this.isShown.bind(this)
this.nextSlide = this.nextSlide.bind(this)
this.pause = this.pause.bind(this)
}
handleActive(id) {
this.setState({
tabId: id
})
}
isShown(num) {
return this.state.tabId === num
}
nextSlide() {
this.setState({
tabId: this.state.tabId + 1 < 5 || 0 ? this.state.tabId + 1 : 1
})
}
pause() {
clearInterval(()=>this.interval)
}
componentDidMount() {
const interval = setInterval(()=> this.nextSlide(),1000)
this.setState({interval: interval})
}
render() {
const data = [
{ id: 1, link: '', mob: '', slide: 'Slide 1', text: 'Slide 1' },
{ id: 2, link: '', mob: '', slide: 'Slide 2', text: 'Slide 2' },
{ id: 3, link: '', mob: '', slide: 'Slide 3', text: 'Slide 3' },
{ id: 4, link: '', mob: '', slide: 'Slide 4', text: 'Slide 4' },
{ id: 5, link: '', mob: '', slide: 'Slide 5', text: 'Slide 5' }
]
const dataLength = data.length
return(
<div >
{console.log(dataLength)}
{console.log(this.state.interval)}
<Bg onMouseEnter={()=>this.pause()}>
{
data.map(item =>
<div>
{
this.isShown(item.id) &&
<div >{item.slide}</div>
}
</div>
)
}
</Bg>
<ul>
{this.state.tabId}
{
data.map(item =>
<li key={item.id} onMouseEnter={() => this.handleActive(item.id)} >
{item.text}
</li>
)
}
</ul>
</div>
)
}
}
答案 0 :(得分:2)
clearInterval
接受您添加到setInterval
中的组件状态的componentDidMount
的结果。
pause() {
clearInterval(this.state.interval);
}
答案 1 :(得分:1)
我通过将间隔添加到我的状态来解决这个问题
constructor() {
super()
this.state = {
tabId: 1,
interval: '',
}
}
handleActive = id => {
this.setState({
tabId: id,
})
}
isShown = num => {
return this.state.tabId === num
}
nextSlide = () => {
this.setState({
tabId: this.state.tabId + 1 < 5 || 0 ? this.state.tabId + 1 : 1,
})
}
handlePause = () => {
this.interval = clearInterval(this.state.interval)
this.setState({ interval: this.interval })
}
handleStart = () => {
this.interval = setInterval(() => this.nextSlide(), 3000)
this.setState({ interval: this.interval })
}
componentDidMount = () => {
this.handleStart()
this.setState({ interval: this.interval })
}
答案 2 :(得分:0)
clearInterval
接受处理程序,而不是function
所以而不是
clearInterval(()=>this.interval)
你应该做
clearInterval(this.state.interval)
也是,而不是
const interval = setInterval(()=> this.nextSlide(),1000)
你可以简单地写
const interval = setInterval(this.nextSlide,1000)