React 组件中的不同区域

Different areas within a React component

可以使用以下语法在 React 中创建组件:

import React, { Component } from 'react';
import ChildComponentOne from './ChildComponentOne';
import ChildComponentTwo from './ChildComponentTwo';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      propOne : '',
      propTwo : '',
      propThree : '',
    };

    this.doThis = this.doThis.bind(this);
    this.doThat = this.doThat.bind(this);
  }

  doThis() {
    ...doingThis code
  }

  doThat() {
    ...doingThat code
  }

  render() {
    return (
      <ChildComponentOne propOne={this.state.propOne} doThis={this.doThis}/>
      <ChildComponentTwo propTwo={this.state.propTwo} propThree={this.state.propThree} doThat={this.doThat}/>
    );
  }
}

export default App;

React 是否使用这种 class 语法,因为他们试图为组织组件制作一个封装和整洁的符号。构造函数方法之后的所有其他内容都以 React 为中心。

或者可以这样写:

App.prototype.doThis = function(){};
App.prototype.doThat = function(){};

function App(){
   this.state = {
      propOne : '',
      propTwo : '',
      propThree : '',
    };

   componentDidMount(){...somecode..}

   componentWillUnmount(){...somecode..}

  render(){
        return (
          <ChildComponentOne propOne={this.state.propOne} doThis={this.doThis}/>
          <ChildComponentTwo propTwo={this.state.propTwo} propThree={this.state.propThree} doThat={this.doThat}/>
        );
  }
}

我知道我离得不远,因为可以只使用一个常规函数来创建所谓的 functional component

猜猜问题是如何利用生命周期方法...

ES6 classes 是函数 classes 的语法糖。当应用程序被转译为 ES5 时,它们实际上变成了函数。

React class 组件应该有 render 方法并且原型继承自 React.Component,这就是它们与功能组件的不同之处。

render最好是原型方法:

App.prototype = Object.create(Component.prototype);
App.prototype.render = function () { ... };

function App(props) { ... }

因为this.render = ...实例方法不合理。也可能是某些第三方库的原型方法。