函数子组件

组件必须有子组件 而且子组件必须为函数,可以在这个组件的生命周期中通过this.props.children访问到该子组件函数,在组件中通过执行该子组件函数来渲染子组件内容,我们只需要负责使用该组件并且完成子组件函数,在函数中return我们需要的内容

class CountDown extends React.Component {

  constructor() {
    super(...arguments);
    this.state = {count: this.props.startCount};
  }

  shouldComponentUpdate(nextProps, nextState) {
    return nextState.count !== this.state.count;
  }

  componentDidMount() {
    this.intervalHandle = setInterval(() => {
      const newCount = this.state.count - 1;
      if (newCount >= 0) {
        this.setState({count: newCount});
      } else {
        window.clearInterval(this.intervalHandle);
        this.intervalHandle = null;
      }
    }, 1000);
  }

  componentWillUnmount() {
    if (this.intervalHandle) {
      window.clearInterval(this.intervalHandle);
      this.intervalHandle = null;
    }
  }

  render() {
    //传入需要的参数 并执行子组件函数
    return this.props.children(this.state.count);
  }
}


使用该组件

<CountDown startCount={10}>
{
    (count) => <div>{count > 0 ? count : "新年快乐"} </div>
}
</CountDown>