React 顶层 API

React 是 React 库的入口。如果你通过使用 <script> 标签的方式来加载 React,则可以通过 React 全局变量对象来获得 React 的顶层 API。当你使用 ES6 与 npm 时,可以通过编写 import React from 'react' 来引入它们。当你使用 ES5 与 npm 时,则可以通过编写 var React = require('react') 来引入它们。

概览

组件

使用 React 组件可以将 UI 拆分为独立且复用的代码片段,每部分都可独立维护。你可以通过子类 React.ComponentReact.PureComponent 来定义 React 组件。

React.Component 是使用ES6 classes方式定义 React 组件的基类:

class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
创建 React 元素

我们建议使用JSX来编写你的 UI 组件。每个 JSX 元素都是调用React.createElement()的语法糖。一般来说,如果你使用了 JSX,就不再需要调用以下方法。

  • createElement()
React.createElement(
  type,
  [props],
  [...children]
)

创建并返回指定类型的新React 元素。其中的类型参数既可以是标签名字符串(如 'div''span'),也可以是React 组件类型 (class 组件或函数组件),或是React fragment类型。

React.Fragment

React.Fragment 组件能够在不额外创建 DOM 元素的情况下,让 render() 方法中返回多个元素。

render() {
  return (
    <React.Fragment>
      Some text.
      <h2>A heading</h2>
    </React.Fragment>
  );
}

你也可以使用其简写语法 <></>

React.createRef

React.createRef 创建一个能够通过 ref 属性附加到 React 元素的 ref

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

    this.inputRef = React.createRef();  }

  render() {
    return <input type="text" ref={this.inputRef} />;  }

  componentDidMount() {
    this.inputRef.current.focus();  }
}
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐