我是新来的反应者,我一直在尝试使用现在的库倒计时为国际象棋创建一个倒数计时器。我目前有一个显示时间的时钟组件。我不知道如何调用启动和停止功能。
这里是库的链接:https://www.npmjs.com/package/react-countdown-now#api-reference
我的时钟组件代码:
function Clock({ time }) {
return (
<div style={clockStyle}>
<Countdown
date={Date.now() + (time * 60000)}
intervalDelay={3}
zeroPadTime={2}
autoStart={false}
daysInHours
/>
</div>
);
}
在父组件中:
<Clock time={state.time} />
从文档中:
倒计时组件通过getApi()函数公开了一个简单的API,可以通过组件ref进行访问。如果需要,它也是传递到渲染器的渲染道具的一部分(api)。
并且一旦我们可以访问API:
start()当autoStart设置为false时,如果暂停或需要倒计时,则开始倒计时。
因此,首先,我们需要访问API(通过ref)
export default class Clock extends React.Component {
render() {
const { refCallback, time } = this.props;
return (
<Countdown
// When the component mounts, this will
// call `refCallback` in the parent component,
// passing a reference to this `Countdown` component
ref={refCallback}
date={Date.now() + (time * 60000)}
intervalDelay={3}
zeroPadTime={2}
autoStart={false}
daysInHours
/>
);
}
}
现在我们可以按照文档中的描述访问API。
class App extends React.Component {
clockRef = null;
constructor(props) {
super(props);
this.setClockRef = this.setClockRef.bind(this);
this.start = this.start.bind(this);
this.pause = this.pause.bind(this);
}
start() {
this.clockRef.start();
}
pause() {
this.clockRef.pause();
}
setClockRef(ref) {
// When the `Clock` (and subsequently `Countdown` mounts
// this will give us access to the API
this.clockRef = ref;
}
render() {
return (
<>
<button onClick={this.start}>Start Clock</button>
<button onClick={this.pause}>Pause Clock</button>
<Clock refCallback={this.setClockRef} time="100" />
</>
);
}
}
单击开始按钮将开始倒数,单击暂停按钮将使倒数开始。