zoukankan      html  css  js  c++  java
  • React的几种组件

    一、函数组件

      该函数在React中是一个有效的组件,可以接收唯一带有数据的props(代表属性)对象,并返回一个React元素。函数式组件要特别注意,组件名称首字母一定要大写。这种方式也成为无状态组件。

      特点有:

      1.组件不会被实例化,整体渲染性能提升了。没有实例化,就不需要分配多余的内存。

      2.不能访问this对象,像this.ref , this.state等不能访问

      3.组件无法访问生命周期方法

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

    二、React.createClass组件

      ES5的原生JavaScript来实现的React组件,与函数式组件相比,React.Componen都是创建有状态的组ss件,这些组件是要被实例化的。并且可以访问组件的生命周期方法。

    var InputControlES5 = React.createClass({
        propTypes: {//定义传入props中的属性各种类型
            initialValue: React.PropTypes.string
        },
        defaultProps: { //组件默认的props对象
            initialValue: ''
        },
        // 设置 initial state
        getInitialState: function() {//组件相关的状态对象
            return {
                text: this.props.initialValue || 'placeholder'
            };
        },
        render: function() {
            return (
                <div>
                    Type something
                </div>
            );
        }
    });

      三、class组件

      更加简洁方便,this指向该组件,可以访问到生命周期函数。数据可通过this.setState()方法进行修改。

    class Welcome extends React.Component {
     constructor(props){
      super(props)//如果要使用props,这是必须的
      }
    render() {
    return <h1>Hello, {this.props.name}</h1>; } }

      四、组件也可以进行组合

      对有状态组件也适用。

    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }
    
    function App() {
      return (
        <div>
          <Welcome name="Sara" />
          <Welcome name="Cahal" />
          <Welcome name="Edite" />
        </div>
      );
    }
    
    ReactDOM.render(
      <App />,
      document.getElementById('root')
    );
  • 相关阅读:
    Vue自带的过滤器
    Spring Boot定时任务应用实践
    iOS中NSDate常用转换操作整合
    iOS中NSFileManager文件常用操作整合
    定位城市的封装
    微信支付和支付宝的封装
    App审核被拒(后台定位被拒,ipv6被拒,广告标示被拒的解决方案)
    按钮图片文字随意摆放
    设备信息大全
    Library not found for -lAPOpenSdk
  • 原文地址:https://www.cnblogs.com/mwxz/p/13524066.html
Copyright © 2011-2022 走看看