【发布时间】:2019-02-01 22:33:16
【问题描述】:
我想构建一个组件,将数字道具随机更新到棋盘上的不同位置。
为了做到这一点,我创建了一个带有间隔的简单组件:
JSFIDDLE:https://jsfiddle.net/ezxnjc8h/
export default class RandomPosition extends React.Component {
constructor(props) {
super(props)
this.interval = null;
this.state = {
x: 0,
y: 0
}
}
componentDidMount() {
this.interval = setInterval(() => {
this.setState({
x: Math.floor(Math.random() * 8),
y: Math.floor(Math.random() * 8)
})
}, 500)
}
componentWillUnmount() {
clearInterval(this.interval)
}
render() {
return <Test knightPosition={[this.state.x, this.state.y]} moveKnight={this.props.moveKnight} />
}
}
我有兴趣使用 withState 和 lifecycle 的重构库将其转换为 Hoc。
JSFIDDLE:https://jsfiddle.net/kzwc9yha/
export default compose(
withState('knightPosition', 'moveKnight', [1,7]),
lifecycle({
componentDidMount() {
this.interval = setInterval(() => {
this.props.moveKnight[Math.floor(Math.random() * 8), Math.floor(Math.random() * 8)]
}, 500)
},
componentWillUnmount() {
clearInterval(this.interval)
}
})
)(Test)
【问题讨论】:
-
能否具体说明您面临的问题
-
对不起,对我来说,这看起来像是在请别人为你写,你能解释一下你尝试了什么吗? :-)