组件, ReactElement 与组件实例

2017-12-14  本文已影响16人  McDu

组件实例是组件类的实例化对象, 通常被用来管理内部状态, 处理生命周期函数.

import ReactDOM from 'react-dom';
import App from './App';
let instance = ReactDOM.render(<App />, document.getElementById('root'));

console.log(App);
console.log(<App />);
console.log(instance);

1. 组件 App

App 就是组件.
控制台打印出来的是:


一个函数或类, 这是一个名为 App 的类, JavaScript 中的类是基于 Function 原型生成的, 所以这里打印了 function App() . 所以组件就是一个函数或类, 它决定了如何把数据变为视图.

2. ReactElement <App/>

type为类

ReactElement 打印出来的是一个普通的对象, 它描述了组件实例或 DOM 节点.

ReactElement 的两种类型

  1. DOM 节点, 当 ReactElementtype 属性为字符串时, 表示DOM 节点, props 属性对应 DOM 节点的属性.
// 在 jsx 中如下打印:
console.log(<h1>hello world</h1>)

得到的 ReactElement 结果为:

type为字符串
  1. 组件, 当 ReactElementtype 属性为函数或类时, 表示组件.

3. 组件实例

  1. ReactDOM.render 返回的就是组件实例, componentDidMount(), componentDidUpdate() 等其他生命周期函数中的 this 都指向组件实例.

  2. 在组件内将方法的 this 的执行上下文绑定在 constructor 中时, this 指向组件实例.

4. ref 与this 指向

由 this 指向组件实例可知,

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

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    this.textInput.focus();
  }

  render() {
    // Use the `ref` callback to store a reference to the text input DOM
    // element in an instance field (for example, this.textInput).
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

React 官网这一节:Refs & the DOM中,下面的 this 指向组件实例:

 ref={(input) => { this.textInput = input; }} />

codesandbox 中运行可知:

小结参考链接

ref 属性可以设置为一个回调函数,这也是官方强烈推荐的用法;这个函数执行的时机为:

  • 组件被挂载后,回调函数被立即执行,回调函数的参数为该组件的具体实例。
  • 组件被卸载或者原有的 ref 属性本身发生变化时,回调也会被立即执行,此时回调函数参数为null,以确保内存不泄露。
    →看我的演示代码→打开相应的 console 即可

参考 <<React-Redux 开发实例精解>>

上一篇 下一篇

猜你喜欢

热点阅读