创新互联React教程:React 组件生命周期

React 组件的生命周期函数,又叫钩子函数,它能响应不同的状态。

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:域名申请、网页空间、营销软件、网站建设、和布克赛尔蒙古网站维护、网站推广。

在本章节中我们将讨论 React 组件的生命周期。

组件的生命周期可分成三个状态:

生命周期的方法有:

这些方法的详细说明,可以参考官方文档。

以下实例在 Hello 组件加载以后,通过 componentDidMount 方法设置一个定时器,每隔100毫秒重新设置组件的透明度,并重新渲染:

class Hello extends React.Component {
 
  constructor(props) {
      super(props);
      this.state = {opacity: 1.0};
  }
 
  componentDidMount() {
    this.timer = setInterval(function () {
      var opacity = this.state.opacity;
      opacity -= .05;
      if (opacity < 0.1) {
        opacity = 1.0;
      }
      this.setState({
        opacity: opacity
      });
    }.bind(this), 100);
  }
 
  render () {
    return (
      
Hello {this.props.name}
); } } ReactDOM.render( , document.body );

尝试一下 »

以下实例初始化 statesetNewnumber 用于更新 state。所有生命周期在 Content 组件中。

class Button extends React.Component {
  constructor(props) {
      super(props);
      this.state = {data: 0};
      this.setNewNumber = this.setNewNumber.bind(this);
  }
  
  setNewNumber() {
    this.setState({data: this.state.data + 1})
  }
  render() {
      return (
         
); } } class Content extends React.Component { componentWillMount() { console.log('Component WILL MOUNT!') } componentDidMount() { console.log('Component DID MOUNT!') } componentWillReceiveProps(newProps) { console.log('Component WILL RECEIVE PROPS!') } shouldComponentUpdate(newProps, newState) { return true; } componentWillUpdate(nextProps, nextState) { console.log('Component WILL UPDATE!'); } componentDidUpdate(prevProps, prevState) { console.log('Component DID UPDATE!') } componentWillUnmount() { console.log('Component WILL UNMOUNT!') } render() { return (

{this.props.myNumber}

); } } ReactDOM.render(
, document.getElementById('example') );

尝试一下 »


网页题目:创新互联React教程:React 组件生命周期
文章起源:http://www.turtgq.com/article/coeidgd.html

其他资讯