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 组件类中的方法:

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

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

  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 数据流向下传递:

2.2.4 类组件示例

    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'));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值