React组件: 展示型组件和容器型组件

227 阅读1分钟

在 React当中,组件的状态(数据)管理是特别重要的,一个好的组件,有良好的数据管理状态。

将组件的展示层剥离出来,仅仅用来进行展示,数据全部从组件外部传递。这样的组件就了层的概念,每个层各自维护自己的内容,符合单一职责原则。

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { time: this.props.time };
    this._update = this._updateTime.bind(this);
  }
  render() {
    const time = this._formatTime( this.state.time);
    return ( 
        <h1>
        { time.hours } : { time.minutes } : { time.seconds }
        </h1>
    ); 
  }
componentDidMount() {
    this._interval = setInterval(this._update, 1000); 
}
componentWillUnmount() { 
    clearInterval(this._interval);
}
_formatTime(time) {
    var [ hours, minutes, seconds ] = [
        time.getHours(),
        time.getMinutes(),
        time.getSeconds()
    ].map(num => num < 10 ? '0' + num : num);
        return { hours, minutes, seconds };
    }
_updateTime() {
        this.setState({time: new Date(this.state.time.getTime() + 1000) });
  } 
};
ReactDOM.render(<Clock time={ new Date() }/>, ...);
// Clock/index.js
import Clock from './Clock.jsx'; // 展示型组件
export default class ClockContainer extends React.Component {
constructor(props) { 
    super(props);
    this.state = { time: props.time };
    this._update = this._updateTime.bind(this); 
}
render() {

    return <Clock { ...this._extra ct(this.state.time) }/>;
}
 componentDidMount() {this._interval = setInterval(t his._update, 1000);}
 componentWillUnmount() {clearInterval(this._interval); }
_extract(time) { return {
    hours: time.getHours(), minutes: time.getMinutes(), seconds: time.getSeconds()
}; }
_updateTime() { 
    this.setState({
        time: new Date(this.state.ti me.getTime() + 1000)
    }); 
}
};
// Clock/Clock.jsx
export default function Clock( props ) {
    var [ hours, minutes, seconds ] =
    [
        props.hours,
        props.minutes,
        props.seconds
    ].map(num => num < 10 ? '0' + num : num);
        return <h1>{ hours } : { minutes} : { seconds }</h1>;
};