React组件单一实例

时间:2019-03-30 13:34:19

标签: reactjs typescript singleton

我有一个由this npm软件包创建的计数器组件。

import * as React from 'react';
import { Theme, createStyles, withStyles, WithStyles } from '@material-ui/core';
import withRoot from '../../../withRoot';
import Countdown, { CountdownRenderProps } from 'react-countdown-now/dist';

const styles = (theme: Theme) =>
  createStyles
  ({});

interface IProps
{}

interface IState
{
    seconds: number;
}

class Counter extends React.Component<IProps & WithStyles<typeof styles>, IState>
{
    constructor(props: IProps & WithStyles<typeof styles>)
    {
        super(props);

        this.state =
        {
            seconds: 60000
        }
    }

    // Random component
    Completionist = () => <span>Time is up!</span>;

    // Renderer callback with condition
    renderer = (props: CountdownRenderProps): JSX.Element =>
    {
        if (props.completed)
        {
            // Render a completed statep
            return this.Completionist();
        }
        else
        {
            // Render a countdown
            return <span>{props.minutes}:{props.seconds}</span>;
        }
    }

    render()
    {
        const css = this.props.classes;
        const seconds = this.state.seconds;

        const Body = () =>
            <Countdown date={Date.now() + seconds} renderer={ this.renderer } />

        return Body();
    }
}

export default withRoot(withStyles(styles)(Counter));

我在项目中需要的是在4个不同页面中的该计数器,该计数器彼此相邻,剩余时间在新页面上。

我的想法是创建一个单例,但失败了。 任何帮助! thnx

1 个答案:

答案 0 :(得分:0)

有两种方法可以做到这一点。您可以将状态向上移动到根元素,然后使用道具将其向下传递到计数器元素。这种方法的问题在于,然后需要在根元素中添加用于增加状态的逻辑,否则将根据您在屏幕上拥有多少个计数器而增加更多的状态。

React实际上并不是要成为一个完整的应用程序框架,它实际上只是用于呈现HTML。如果您想正确地管理应用程序状态,则应该使用Redux之类的东西,它可以与React很好地交互,并为您提供很大的灵活性。此处更多内容:https://redux.js.org/introduction/getting-started

相关问题