React入门-3.组件

1. 组件介绍

组件容许咱们将UI拆分为独立的、可重用的部分,并独立地考虑每一个部分。数组

2. 组件定义

2.1. 函数组件

定义个组件的最简单的方式就是写一个Javascript函数。该函数接受一个对象做为参数(咱们称之为props,该参数为只读参数),而且返回一个React Element闭包

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

2.2. 类组件

2.2.1 组件类中的方法:app

  1. render() 主要渲染返回,用于返回一个React Component
  2. constructor(props) 构造函数方法,该方法中必须显式调用super(props)
  3. componentDidMount() 组件挂载时的钩子函数
  4. componentWillUnmount() 组件卸载时的钩子函数

2.2.2 组件类中的属性:
state:用于维护实例变量,全部的方法均可以访问该实例变量中的值。实际上这就组成了一个闭包。在使用state的时候须要明确几点dom

  1. 不要试图直接修改state的值,而是经过setState方法。只能在构造函数中对state进行赋值操做异步

    // Wrong
    this.state.comment = 'Hello';
    // Correct
    this.setState({comment: 'Hello'});
  2. state状态的更新多是异步的,能够使用另一种方式修改state的值函数

    // Correct
    this.setState((state, props) => ({
        counter: state.counter + props.increment
    }));

2.2.3 数据流向下传递:this

2.2.4 类组件示例code

class Welcome extends React.Component {
      //构造函数,在构造函数第一行要调用super
      constructor(props){
        super(props);
        this.state = {date:new Date()}
      }
      //组件绑定的时候设置间歇调用,每隔一秒钟修改date值
      componentDidMount(){
        this.timerID = setInterval(
          () => this.tick(),
          1000
        );
      }
      //组件卸载时取消简写调用
      componentWillUnMount(){
        clearInterval(this.timerID);
      }
      //修改date值
      tick(){
        this.setState({
          date: new Date()
        });
      }
      //渲染,当state中的值发生变化的时候DOM中对应的值也会发生变化
      render(){
        return <h1>hello {this.state.date.toLocaleTimeString()}</h1>
      }
    }

    ReactDOM.render(<Welcome/>,document.getElementById('app'));

4. 组件使用

4.1 组件定义好了,经过标签来调用组件,而且组件属性能够被设置到props中。

function Welcome(props){
      return <h1>hello {props.name}</h1>
    }

    const dom = <Welcome name='terry'/> 
        ReactDOM.render(dom, document.getElementById('app')
    );

4.2 组件嵌套使用

//定义Welcome组件
    function Welcome(props){
      return <h1>hello {props.name}</h1>
    }
    //在App中使用Welcome组件
    function App(props){
      return (
        <div>
          <Welcome name='terry'/> 
          <Welcome name='larry'/> 
          <Welcome name='tom'/> 
        </div>
      );
    }
    //
    const dom = <App/> ;
    ReactDOM.render( dom,document.getElementById('app'));
相关文章
相关标签/搜索