React Supplements (lower)

JSX depth

In essence, JSX just syntactic sugar provided for the React.createElement (component, props, ... children) method.

E.g:

<MyButton color="blue" shadowSize={2}>
  Click Me
</MyButton>

Compile as follows:

React.createElement(
  MyButton,
  {color: 'blue', shadowSize: 2},
  'Click Me'
)

If no offspring, self-closing tags may also be used:

<div className="sidebar" />

Compile as follows:

React.createElement(
  'div',
  {className: 'sidebar'},
  null
)

Therefore, you must use the JSX:

  1. React must be declared. Since the method is invoked React.createElement JSX after compiling, you must first declare React JSX variable in your code.
  2. React specified element type. Tag indicates the beginning of the upper case JSX React a component, these labels will be compiled into a variable of the same name and reference; and when the element type start with a lowercase letter, which represents a built-in component, such as
    Or .

Check the type of use PropTypes

PropTypes comprising a set of verification, which can be used to ensure that you receive data is valid. When you pass an invalid value to the property, JavsScript console will print a warning. For performance reasons, propTypes only be checked in development mode.

The following are examples of the use of different validators:

import PropTypes from 'prop-types';

MyComponent.propTypes = {
  // 你可以将属性声明为以下 JS 原生类型
  optionalArray: PropTypes.array,
  optionalBool: PropTypes.bool,
  optionalFunc: PropTypes.func,
  optionalNumber: PropTypes.number,
  optionalObject: PropTypes.object,
  optionalString: PropTypes.string,
  optionalSymbol: PropTypes.symbol,

  // 任何可被渲染的元素(包括数字、字符串、子元素或数组)。
  optionalNode: PropTypes.node,

  // 一个 React 元素
  optionalElement: PropTypes.element,

  // 你也可以声明属性为某个类的实例,这里使用 JS 的
  // instanceof 操作符实现。
  optionalMessage: PropTypes.instanceOf(Message),

  // 你也可以限制你的属性值是某个特定值之一
  optionalEnum: PropTypes.oneOf(['News', 'Photos']),

  // 限制它为列举类型之一的对象
  optionalUnion: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Message)
  ]),

  // 一个指定元素类型的数组
  optionalArrayOf: PropTypes.arrayOf(PropTypes.number),

  // 一个指定类型的对象
  optionalObjectOf: PropTypes.objectOf(PropTypes.number),

  // 一个指定属性及其类型的对象
  optionalObjectWithShape: PropTypes.shape({
    color: PropTypes.string,
    fontSize: PropTypes.number
  }),

  // 你也可以在任何 PropTypes 属性后面加上 `isRequired` 
  // 后缀,这样如果这个属性父组件没有提供时,会打印警告信息
  requiredFunc: PropTypes.func.isRequired,

  // 任意类型的数据
  requiredAny: PropTypes.any.isRequired,

  // 你也可以指定一个自定义验证器。它应该在验证失败时返回
  // 一个 Error 对象而不是 `console.warn` 或抛出异常。
  // 不过在 `oneOfType` 中它不起作用。
  customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  },

  // 不过你可以提供一个自定义的 `arrayOf` 或 `objectOf` 
  // 验证器,它应该在验证失败时返回一个 Error 对象。 它被用
  // 于验证数组或对象的每个值。验证器前两个参数的第一个是数组
  // 或对象本身,第二个是它们对应的键。
  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.'
      );
    }
  })
};

Property Default

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

// 为属性指定默认值:
Greeting.defaultProps = {
  name: 'Stranger'
};

// 渲染 "Hello, Stranger":
ReactDOM.render(
  <Greeting />,
  document.getElementById('example')
);

defaultProps this.props.name to ensure in the case of the parent component, unless otherwise specified, there is an initial value. DefaultProps type checking occurs after the assignment, the type checking is also applied in defaultProps above.

Refs & DOM

Add Ref DOM element

React to support any of the components to add special properties. The ref attribute accepts a callback function that will be executed immediately when the component is loaded or unloaded.

When added to the HTML attribute element ref, ref callback underlying DOM elements received as parameters. For example, the following code is used to store a callback ref DOM node references.

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
  }

  focus() {
    // 直接使用原生 API 使 text 输入框获得焦点
    this.textInput.focus();
  }

  render() {
    // 使用 `ref` 的回调将 text 输入框的 DOM 节点存储到 React 
    // 实例上(比如 this.textInput)
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focus}
        />
      </div>
    );
  }
}

React assembly while loading the DOM element passed ref callback function, when you uninstall will be passed null.

Add component class Ref

When the ref attribute for custom components using the class declaration, ref callback is received React instance already loaded.

And functional components Refs

You can not use the ref attribute on the functional components because they do not have instances. However, you can use the functional components inside the ref, so long as it points to a class DOM element or component.

Parent node assembly is exposed DOM

In rare cases, you may want to DOM nodes from the parent component to access child nodes. In this case, we recommend exposure to a particular property on the child nodes. Function will get a child node attribute, and attached to the DOM node as the ref attribute. This allows the parent by the middleware to the ref callback offspring DOM node.

E.g:

function CustomTextInput(props) {
  return (
    <div>
      <input ref={props.inputRef} />
    </div>
  );
}

class Parent extends React.Component {
  render() {
    return (
      <CustomTextInput
        inputRef={el => this.inputElement = el}
      />
    );
  }
}

Another advantage of this model is that it can effect deep. The layers may be transmitted through the props properties, allowing access to their progeny parent component assembly DOM node.

note

If the ref callback within the definition of an inline function the way it will be called twice during the update, the first argument is null, then the parameter is a DOM element. This is because the function creates a new instance of each rendering. Therefore, React need to clean up the old ref and set up new ones. By way binding function callback ref defined as a class to avoid these problems, but it does not matter in most cases.

reconciliation (coordination algorithm)

react algorithm used to update the DOM. Based on two assumptions, it implements a heuristic of O (n) algorithm:

  1. Two different types of elements will produce different trees.
  2. By renderer included with keyproperty developers which can be schematically sub-elements may be stable.

Elements of different types

When comparing two trees, React root node first compares the two. Whenever root element there are different types, React to uninstall the old tree and re-build a new tree.

When the tree is unloaded, the old DOM node will be destroyed. Examples of the component will be received componentWillUnmount () method. When building a new tree, new DOM node is inserted into the DOM. Examples of the component received componentWillMount () and subsequent componentDidMount (). Any state about the old tree will be discarded.

For example, when comparison:

<div>
  <Counter />
</div>

<span>
  <Counter />
</span>

This will destroy the old Counter and reinstall the new node.

DOM element of the same type

When comparing two elements of the same type React DOM, React property will both observed, maintaining the same underlying DOM node, and updates only the attribute change. (For example, change the class name, style, etc.)

After processing the DOM element, React its children recursively.

Recursive child node

The default time. When the child nodes recursively DOM node, React only two child nodes recursively list at the same point in time, and there does not produce a change at the same time.

For example, when adding an element to the end of the child nodes, transitions well two trees:

<ul>
  <li>first</li>
  <li>second</li>
</ul>

<ul>
  <li>first</li>
  <li>second</li>
  <li>third</li>
</ul>

React will match two trees

  • first
  • And matching two trees
  • second
  • Node, and insert
  • third
  • Node tree.

    When the native implementation, the start will make it more difficult to insert elements properties. For example, the effect of the conversion of two trees are relatively poor:

    <ul>
      <li>Duke</li>
      <li>Villanova</li>
    </ul>
    
    <ul>
      <li>Connecticut</li>
      <li>Duke</li>
      <li>Villanova</li>
    </ul>

    React adjusts each child node, rather than be aware intact

  • Duke
  • with
  • Villanova
  • Subtree. Inefficiency becomes an issue.

    Keys

    To solve this problem, React support a key attribute. When there is a child node key, React use the key to match the original child nodes of the tree and the new tree of child nodes. For example, a key to make increase the conversion efficiency of the tree before the sample becomes high efficiency:

    <ul>
      <li key="2015">Duke</li>
      <li key="2016">Villanova</li>
    </ul>
    
    <ul>
      <li key="2014">Connecticut</li>
      <li key="2015">Duke</li>
      <li key="2016">Villanova</li>
    </ul>

    React now know the key element with '2014' is new, and only the move key element with '2015' and '2016' the.

    trade off

    Since React rely on the heuristic algorithm, assuming behind not met, its performance will be affected:

    1. Algorithms can not try to match different component types of child elements. If you find two very similar output alternating component type, you might want to make it the same type. In practice, we found that this is not a problem.
    2. Keys should be stable, predictable, and unique. Unstable key (similar to the Math.random()generation of) a large number of component instances and will cause unnecessary reconstruction DOM node, so that performance degradation and loss of state subassembly.

    Portals

    Portals provide a good render child node to the parent DOM nodes other than the component approach.

    ReactDOM.createPortal(child, container)

    The first parameter (Child) React any child elements can render such an element, string or debris. The second parameter (Container) is a DOM element.

    usage

    Typically speaking, when you render method returns an element from the assembly, the assembly element only DOM node from its nearest parent element

    render() {
      // React mounts a new div and renders the children into it
      return (
        <div>
          {this.props.children}
        </div>
      );
    }

    However, sometimes it is inserted into a DOM node different positions is also useful:

    render() {
      // React does *not* create a new div. It renders the children into `domNode`.
      // `domNode` is any valid DOM node, regardless of its location in the DOM.
      return ReactDOM.createPortal(
        this.props.children,
        domNode,
      );
    }

    For a typical portal use case is when a parent component has overflow: hidden or z-index style, but you need to be able to visually subassembly "jump (break out)" of its container. For example, dialog boxes, hovercards and prompt box.

    For event bubbling through Portals

    Although the portal can be placed anywhere in the DOM tree, but consistent with other aspects of their behavior and the behavior of ordinary React child nodes. Such as context characteristics can still work the same as before correctly, regardless of whether its child nodes are portal, because the portal is still present React tree, regardless of its position in the DOM tree.

    This includes event bubbling. An event that will trigger from within the portal will always bubbling to contain React ancestry tree.

    Guess you like

    Origin www.cnblogs.com/simpul/p/11440749.html