Component

在前面的章节中,咱们学习了如何使用jsx语法建立基本元素,实际上,在React中,还能够经过组件的方式来构建用户界面,下面咱们就来看一下,如何来定义组件。javascript

组件定义

function

第一种方式,咱们可使用function来定义一个组件,如:java

const Welcome = props => {
  return <h1>hello, {props.name}!</h1>
}

Welcome函数就是一个React组件,这个函数接收props做为参数,用来标志组件须要的外部数据,同时,组件返回了一个React元素。node

class

第二种方式,咱们可使用ES6中的class来定义:数组

class Welcome extends React.Component {
  render() {
    return <h1>hello, {this.props.name}!</h1>
  }
}

class定义的组件中,咱们首先要继承React.Component,继承Component能够初始化组件的props,而后还须要实现一个render方法,用来返回这个组件的结构,也就是使用function定义组件的那个返回值。若是还须要使用到外部数据的话,能够经过this.props来获取。babel

对于React来讲,这两种方式是等价的,可是经过class定义的组件还有一些额外的特性,咱们会在后面的章节介绍。ide

组件渲染

咱们知道,React完成一个基本元素的渲染,首先须要经过React.createElement建立一个描述对象,而后ReactDOM再根据这个描述对象,生成真实DOM渲染在页面上。实际上,针对组件的渲染也是这样。所以,咱们首先要建立组件的描述对象:函数

const element = React.createElement(Welcome, {
  name: "Sara"
})

React.createElement不但能够建立基本元素,还能够针对组件来进行建立。学习

图片描述

在控制台上打印这个对象,能够看到,该对象的type属性就是我们刚刚建立的Welcome类,props属性就是这个组件所需的外部参数。ui

除了能够经过React.createElement来建立组件的描述对象之外,咱们还可使用jsxthis

const element = <Welcome name="Sara" />

使用 jsx 的话,咱们能够直接将须要传递给组件的数据,定义在标签身上,而后babel在解析时,会把这个标签上的属性收集起来,当成props传递给组件。组件内部就能够经过this.props访问了。

最后,咱们再将这个元素交给ReactDOM渲染出来:

ReactDOM.render(element, document.querySelector("#root"))

图片描述

复合组件

在组件中,除了返回一些基本元素之外,还能够嵌套其余的组件,咱们称之为复合组件,例如:

class App extends React.Component {
  render() {
    return (
      <div> {/* 顶级组件 */}
        <Welcome name="Sara" />
        <Welcome name="Cahal" />
        <Welcome name="Edite" />
      </div>
    )
  }
}
ReactDOM.render(<App />, document.querySelector("#root"))

以上示例,在<App />组件中,屡次使用 <Welcome />组件。当一个组件是由多个子元素或者组件组成的时候,全部子元素必须包含在一个顶级组件中,因此咱们不能这样写:

// 错误示范,缺乏顶级组件
class App extends React.Component {
  render() {
    return (
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    )
  }
}

控制台提示:

图片描述

所以,咱们建立的组件必须有一个顶级组件给包裹起来。那这时,页面渲染出来的真实结构就是这个样子:

图片描述

能够看到,在根元素root下面是一个div,而后才是多个h1元素。有时候,组件中的这个顶级元素在整个页面中是多余的,咱们并不但愿在页面中建立这个节点,这时,咱们可使用React.Fragement来充当顶级元素:

class App extends React.Component {
  render() {
    return (
      <React.Fragment>{/* 顶级组件 */}
        <Welcome name="Sara" />
        <Welcome name="Cahal" />
        <Welcome name="Edite" />
      </React.Fragment>
    )
  }
}

这时,页面渲染的时候,就不会产生多余的DOM节点了。

图片描述

甚至,咱们还能够直接使用<>...</>来简化它。

class App extends React.Component {
  render() {
    return (
      <>{/* 顶级组件 */}
        <Welcome name="Sara" />
        <Welcome name="Cahal" />
        <Welcome name="Edite" />
      </>
    )
  }
}

这两种方式是等价的。

Props

defaultProps

咱们知道,props是组件内部接收外部数据的一种方式,但有时,外部没有提供有效数据时,有可能会致使组件渲染时出错,例如:

class Books extends React.Component {
  render() {
    return (
      <>
        <h1>Books:</h1>
        <ul>
          {
            this.props.books.map(item => {
              return <li key={item}>{item}</li>
            })
          }
        </ul>
      </>
    )
  }
}

ReactDOM.render(<Books />, document.querySelector("#root"))

<Books />组件,接收一个数组做为参数,组件内部迭代数组产生子元素,可是咱们使用<Books />组件时,并无传递任何数据给该组件,因此致使this.props.books.map方法调用失败,为了防止此类错误,React容许咱们给props设置默认值。

/* 定义 props 的默认值 */

// 方式一:
class Books extends React.Component {
  static defaultProps = {
    books: []
  }
  ...
}
// 方式二:
Books.defaultProps = {
  books: []
}

咱们能够经过设置类的静态属性defaultProps,来设置props的默认值。

propTypes

除了给props设置默认值之外,还能够添加props的类型约束,例如,咱们能够设置books的类型为Array:

import PropTypes from 'prop-types';

class Books extends React.Component {
  ...

  static propTypes = {
    books: PropTypes.array
  }
  
  ...

}
ReactDOM.render(<Books books="test" />, document.querySelector("#root"))

React提供了一个PropTypes对象,用来对数据类型进行检测,在这个示例中,咱们设置了props.books的类型为PropTypes.array,但实际传入了一个字符串,控制台就有如下提示:

图片描述

如下是PropTypes提供的数据类型:

import PropTypes from 'prop-types';

MyComponent.propTypes = {
  // You can declare that a prop is a specific JS type. By default, these
  // are all optional.
  optionalArray: PropTypes.array,
  optionalBool: PropTypes.bool,
  optionalFunc: PropTypes.func,
  optionalNumber: PropTypes.number,
  optionalObject: PropTypes.object,
  optionalString: PropTypes.string,
  optionalSymbol: PropTypes.symbol,

  // Anything that can be rendered: numbers, strings, elements or an array
  // (or fragment) containing these types.
  optionalNode: PropTypes.node,

  // A React element.
  optionalElement: PropTypes.element,

  // You can also declare that a prop is an instance of a class. This uses
  // JS's instanceof operator.
  optionalMessage: PropTypes.instanceOf(Message),

  // You can ensure that your prop is limited to specific values by treating
  // it as an enum.
  optionalEnum: PropTypes.oneOf(['News', 'Photos']),

  // An object that could be one of many types
  optionalUnion: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Message)
  ]),

  // An array of a certain type
  optionalArrayOf: PropTypes.arrayOf(PropTypes.number),

  // An object with property values of a certain type
  optionalObjectOf: PropTypes.objectOf(PropTypes.number),

  // An object taking on a particular shape
  optionalObjectWithShape: PropTypes.shape({
    color: PropTypes.string,
    fontSize: PropTypes.number
  }),

  // You can chain any of the above with `isRequired` to make sure a warning
  // is shown if the prop isn't provided.
  requiredFunc: PropTypes.func.isRequired,

  // A value of any data type
  requiredAny: PropTypes.any.isRequired,

  // You can also specify a custom validator. It should return an Error
  // object if the validation fails. Don't `console.warn` or throw, as this
  // won't work inside `oneOfType`.
  customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  },

  // You can also supply a custom validator to `arrayOf` and `objectOf`.
  // It should return an Error object if the validation fails. The validator
  // will be called for each key in the array or object. The first two
  // arguments of the validator are the array or object itself, and the
  // current item's key.
  customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
    if (!/matchme/.test(propValue[key])) {
      return new Error(
        'Invalid prop `' + propFullName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  })
};
相关文章
相关标签/搜索