ReactJS基础(续)

前边的ReactJS基础,我们可以了解到,对于React,可以说是万物皆组件

React的组件应该具有 可组合(Composeable)可重用(Reusable)可维护(Maintainable)的特征,所以我们尽量将组件最小化,写的尽可能的小

前边已经介绍了组件的写法,下面我们来进一步了解一下组件的属性、状态、生命周期和嵌套

组件的属性

我们来编写一个组件SayHello,有一个name属性,然后输出hello + name的值,代码如下:

var SayHello = React.createClass({
    render:function(){
        return <h1 style={{color:"red"}}>hello {this.props.name}</h1>
    }
});

ReactDOM.render(
    <SayHello name="lyx" />,
    document.getElementById('great')
)

 结果

有些细节需要注意:

1.创建的组件名称首字母必须大写。
2.<SayHello name="lyx" />与 document.getElementById('great')之间用的是逗号分隔

   3.获取属性的值用的是 this.props.属性名

   4.组件的style属性的设置方式也值得注意,要写成style={{“”100"}}这种形式

 组件的状态

组件免不了要与用户互动,React 的一大创新,就是将组件看成是一个状态机,一开始有一个初始状态,然后用户互动,导致状态变化,从而触发重新渲染 UI 。我们来看代码

var Counter = React.createClass({
  getInitialState: function () {
    return { clickCount: 0 };
  },
  handleClick: function () {
    this.setState(function(state) {
      return {clickCount: state.clickCount + 1};
    });
  },
  render: function () {
    return (<h2 onClick={this.handleClick}>点我!点击次数为: {this.state.clickCount}</h2>);
  }
});

上面代码实现的是点击h2,显示点击次数,效果如图所示

需要注意是的是

1.getInitialState函数必须有返回值,可以是NULL或者一个对象。

2.访问state的方法是this.state.属性名。

3.变量用 { }包裹,不需要再加双引号。

组件的嵌套

前边我们说了,组件要有复用的特点,线面来看一下如何复用

来看下边的代码

var Form= React.createClass({
    render:function(){
        return <div>
        {this.props.inputName}:<input type="text"/>
        
        </div>
    }
});
var Iname= React.createClass({
    render : function(){
        return <div>
            <h3>欢迎</h3>
            <Form inputName="姓名"/>
            <Form inputName="电话"/>
            <button>submit</button>
        </div>
    }
});
ReactDOM.render(
    <Iname />,
    document.getElementById('sub')
)

这里我们创建了一个Form组件,然后又创建了一个Iname组件,然后我们在Inmae组件中调用Form组件两次,这里我们通过属性inputName传入值

 组件生命周期

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

  • Mounting:已插入真实 DOM
  • Updating:正在被重新渲染
  • Unmounting:已移出真实 DOM

生命周期的方法有:

componentWillMount 在渲染前调用,在客户端也在服务端。

componentDidMount : 在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行访问。 如果你想和其他JavaScript框架一起使用,可以在这个方法中调用setTimeout, setInterval或者发送AJAX请求等操作(防止异部操作阻塞UI)。

componentWillReceiveProps 在组件接收到一个新的prop时被调用。这个方法在初始化render时不会被调用。

shouldComponentUpdate 返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。
可以在你确认不需要更新组件时使用。

componentWillUpdate在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。

componentDidUpdate 在组件完成更新后立即调用。在初始化时不会被调用。

componentWillUnmount在组件从 DOM 中移除的时候立刻被调用。

这些就跟PHP中的一些魔术方法一样,满足条件自动调用,

下面以componentDidMount方法为例,

var Hello = React.createClass({
  getInitialState: function () {
    return {
      color: "red"
    };
  },
 
  componentDidMount: function () {
   
         alert("111");
  
  },
 
  render: function () {
    return (
      <div style={{color: this.state.color}}>
        Hello {this.props.name}
      </div>
    );
  }
});

此方法是第一次渲染后调用,就有如下结果

原文地址:https://www.cnblogs.com/cherishli/p/7107561.html