React Supplements (on)

JSX on behalf of Objects

Babel will escape JSX is converted into a method named React.createElement () call.

The following effects of the two codes are identical:

const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
);
const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);

React.createElement () This method first checks some avoid the bug, then returns a similar object the following example:

// 注意: 以下示例是简化过的(不代表在 React 源码中是这样)
const element = {
  type: 'h1',
  props: {
    className: 'greeting',
    children: 'Hello, world'
  }
};

Such objects are called "React elements." It represents everything you see on the screen. React DOM constructed by reading the content data object and to maintain consistency.

Props are read-only

Whether you use a function or class to declare a component that must not modify its own props. All React components must use them as props like a pure function.

Top-down data flow

Parent component or sub-assembly can not know whether a component is stateful or stateless, and they should not be concerned about a component is defined as a function or a class.

This is why the state is generally referred to as local or encapsulated. In addition to having set and its components, the other components are not accessible.

This is commonly referred to as top-down or unidirectional data flow. Any state always made certain that all components, and any data or derived from the UI state can only affect components beneath the tree.

Prevent component rendering

In rare cases, you may want to hide components, even if it is rendered other components. Let render method returns null instead of rendering its results can be realized.

But it should be noted that, render the component method returns null and does not affect the life cycle callback method of the component.

Enhance the status

React in, the state is shared by the component state data up to the data required from the closest parent to complete assembly. This is called the status upgrade .

React in the application, correspond to any variable data should only a single "data sources." In general, states are required to render first add the component data. In this case, if the other components are also required these data, you can upgrade to the data from their nearest parent component. You should keep the data flow from top to bottom in the application, rather than try to synchronize state in different components.

VS combination of inheritance

React with a powerful combination model, we recommend the use of combination rather than inheritance to reuse code between the components used.

Inclusion relation

Use children property sub-elements are passed directly to the output

function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color}>
      {props.children}
    </div>
  );
}
function WelcomeDialog() {
  return (
    <FancyBorder color="blue">
      <h1 className="Dialog-title">
        Welcome
      </h1>
      <p className="Dialog-message">
        Thank you for visiting our spacecraft!
      </p>
    </FancyBorder>
  );
}

Though less common, but sometimes you may want to have multiple inlets in the assembly, in which case you can use your own property instead of the agreed children:

function SplitPane(props) {
  return (
    <div className="SplitPane">
      <div className="SplitPane-left">
        {props.left}
      </div>
      <div className="SplitPane-right">
        {props.right}
      </div>
    </div>
  );
}

function App() {
  return (
    <SplitPane
      left={
        <Contacts />
      }
      right={
        <Chat />
      } />
  );
}

So inherit it?

On the Facebook site, use our React thousands of components, but it has not found any case need to recommend that you use inheritance.

Property and combination provides all the flexibility and security in a clear way from the style and behavior of components required for you. Remember that the component can accept any element, including basic data types, elements or functions React.

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.

Guess you like

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