react

Facebook开发的一个js库,主要用来构建UI。

教程

IBM简要介绍 https://www.ibm.com/developerworks/cn/web/1509_dongyue_react/index.html

官方教程:
https://reactjs.org/tutorial/tutorial.html

菜鸟教程:
http://www.runoob.com/react/react-tutorial.html

配置使用:
https://zhenyong.github.io/react/docs/getting-started.html

学习

关键词:

组件component
虚拟DOM
数据的单向流动

特点:

React 中的基本概念

使用:

使用的基本流程是:
创建component,
各种component各种组合composition;
显示components。

  1. 两种component创建
    一种是无状态变化的,使用正常的js function语法,return JSX 即可。
    const DemoComponent = function() {
      return (
     <div className='customClass' />
      );
    };
    

另一种则是有状态变化的常用的React Component。

class Kitten extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <h1>Hi</h1>
    );
  }
}

React的一个重要的特色就是通过component的各种组合来实现所需功能。

return (
<App>
  <Navbar />
  <Dashboard />
  <Footer />
</App>
)
  1. 定义默认props并进行类型检查:
    MyComponent.defaultProps = { location: 'San Francisco' }
    MyComponent.propTypes = { handleClick: PropTypes.func.isRequired }
    
  2. State参数的使用

State是react中一个很重要的概念,用来跟踪组件内部重要数据或状态的变化,进一步控制UI render。且state参数只对拥有它的component可见,除非它作为props传递给子组件。可以使用this.state来获取state参数的值并使用。

this.setState({
  username: 'Lewis'
});
  1. 父子组件间参数的传递

可以将全部的state或部分的state通过props传给子组件。

在父组件中:<Navbar name={this.state.name} />
子组件中:<h1>Hello, my name is: {this.props.name} </h1>

父子组件之间除了可以通过state-props传递数据之外,还可以传递handle function。
传递function的方式和传递state date的方式相似。

  1. 为component定义method:

除了在component中通过定义和更新state来管理数据外,还可以给组件定义方法。
多数情况定义event handler function,为了能够访问组件内部的成员和数据,要使用this来绑定。
this.handleClick = this.handleClick.bind(this)
通过state+ method,可以实现很多功能。

  1. controlled input and form

如果你的component中包含由用户输入信息的元素,可以为input, textarea此类元素,也可以为整个form,那么这个component就被称为controlled component。
React可以很好的管理这些涉及用户输入的元素的状态,根据state, event handler来很好的处理。

7.lifecycle methods

可参考 https://github.com/axuebin/react-blog/issues/9

React提给了很多在component整个生命周期中某个特定时刻运行的函数,称为lifecycle methods, or lifecycle hooks, 允许在某些特定时刻截获组件进行处理。
主要有:

componentWillMount()

componentDidMount()

componentWillReceiveProps()

shouldComponentUpdate()

componentWillUpdate()

componentDidUpdate()

componentWillUnmount()

React组件的生命周期可以分为挂载、渲染和卸载这几个阶段,当渲染后的组件更新后,会重新渲染组件,直到卸载。

挂载阶段(Mounting)
属于这个阶段的生命周期函数有:

1.constructor()
2.componentWillMount()
3.render()
4.componentDidMount()

更新阶段(Updating)
属性或状态的改变会触发一次更新。当一个组件在被重新渲染时,这些方法将会被调用:

1.	componentWillReceiveProps()
2.	shouldComponentUpdate()
3.	componentWillUpdate()
4.	render()
5.	componentDidUpdate()

卸载阶段
该方法将会在 component 从DOM中移除时调用
componentWillUnmount()

lifecycle method 详解

周期图(https://www.jianshu.com/p/b49fe87d2153)