javascript - React 组件中的不同区域

标签 javascript reactjs class prototype

可以使用以下语法在 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}/>
        );
  }
}

我知道我离得不远,因为可以只利用一个常规函数来创建所谓的功能组件

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

最佳答案

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

React 类组件应该有 render 方法,并且原型(prototype)继承自 React.Component,这就是它们与函数式组件的不同之处。

render 最好是原型(prototype)方法:

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

function App(props) { ... }

因为 this.render = ... 实例方法不合理。也有可能被一些第三方库认为是原型(prototype)方法。

关于javascript - React 组件中的不同区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53786399/

相关文章:

c# - 为什么 Exception 是一个类,而不是一个结构?

javascript - CSS 覆盖关闭按钮滚动到页面顶部

编程面试中的 Javascript 和优先队列

javascript - jquery 对话框在单击按钮时打开新实例

javascript - 如果文件已经存在于javascript中,如何增加文件名

使用数组和 arrayList 的 Java 类

javascript - 子弹不会从枪管中射出

javascript - React Native 中组件之间的通信(子 -> 父)

javascript - 如何使用react-redux将ReactJS组件正确连接到Redux?

C++ : Swapping template class elements of different types?