猿问

如何在 react-bootstrap-table-next 表的列中显示倒计时?

我目前在 react-bootstrap-table-next 表中有一个列显示过期日期。这是我定义列的方式:


    const columns = [{

      ...

    }, {

      dataField: 'expiresAt',

      text: 'Expires',

      formatter: timestampFormatter

    }];

(...为简洁起见,我用 替换了其他列。)


这是 timestampFormatter 函数:


    function timestampFormatter(cell, row) {

      if (cell == null) {

        return cell;

      } else {

        return (moment(cell).utcOffset(cell).local().format('llll'));

      }

    }

下面是此列中一个单元格现在的样子的示例:

我想用倒计时替换这些单元格,显示天数、小时数和分钟数(如果还剩不到一分钟,则显示秒数)直到到期。我当然可以编写代码来创建一个字符串。但我不知道如何让此列中的单元格每秒更新一次。


我可以timestampFormatter用这样的东西替换:


    function countdownFormatter(cell, row) {

      return (

        <Countdown expires={cell} />

      );

    }

...并在 Countdown 组件的 render 方法中计算倒计时字符串。但是由于组件的 props 永远不会改变,它们不会重新渲染。


我可以做这样的事情:


    function countdownFormatter(cell, row) {

      countdownString = countdownFromExpiration(cell);

      return (

        <Countdown countdown={countdownString} />

      );

    }

但是后来我不知道如何安排 countdownFormatter 函数以使其每秒都被调用。


莫回无
浏览 361回答 1
1回答

慕标琳琳

Code Maniac对我的问题的评论建议使用 setTimeOut 为我提供了自己解决其余问题所需的一切。正如我在问题中所考虑的那样,我确实创建了一个倒计时组件。这是我想出的代码:class Countdown extends Component {&nbsp; state = {&nbsp; &nbsp; timeRemainingString: getTimeRemainingString(this.props.expires)&nbsp; };&nbsp; componentDidMount() {&nbsp; &nbsp; this.updateState();&nbsp; }&nbsp; updateState() {&nbsp; &nbsp; this.setState({ timeRemainingString:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; getTimeRemainingString(this.props.expires) });&nbsp; &nbsp; this.timeout = setTimeout(() => { this.updateState() }, 1000);&nbsp; }&nbsp; componentWillUnmount() {&nbsp; &nbsp; clearTimeout(this.timeout);&nbsp; };&nbsp; render() {&nbsp; &nbsp; return ( this.state.timeRemainingString );&nbsp; }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答