ReactJs中Props in Class和功能组件的区别是什么?

问题描述 投票:1回答:1

我看到了这篇文章

https:/overreacted.iohow-are-function-components-different-from-classes。

很有意思,但有一点我想问,我有点明白,但想通过多探讨一些这方面的文章来挖掘更多的东西,尤其是,道具与 "这个 "挂钩是什么意思?区别来自于闭合的方式吗 ? 这有点模糊,我想我不太明白render方法是如何工作的,以及在类中调用方法时变量是如何被堆叠的......。

有谁能帮我找到更多关于这个问题的文章吗?

reactjs render react-props
1个回答
2
投票

你必须注意,类是实例化的,而Function组件是执行的。

现在,当实例化一个类时,React会获取属性,即附加在组件的每个实例上的道具,并将其设置为React.Component中的一个类属性,类似于

class React.Component {
   constructor(props) {
       this.props = props;
   }

   ...
}

而且由于类组件扩展了React.Component,你也可以使用 this 参考

然而,功能组件工作在闭包上,当执行功能组件时,道具作为参数传递给功能组件。

const MyComponent = (props) => {
   console.log(props)
}

Javacript中的类工作于 prototypes. 渲染方法在你的类组件中被定义为一个函数,在其生命周期中被React.Component调用。然而对于一个功能组件来说,整个主体都可以被认为是一个render方法

然而,随着钩子的到来,更多的关注点是在功能组件中提供类似于生活方式的实用工具,但基本的设计仍然是相同的。


0
投票

你好,关于闭包和作用域,钩子是函数组件,因此,如果你想从外部作用域访问一个变量,那么闭包将以类似于javascript forexample的方式进行。

function Example (){
      const [exampletypes, setExampletypes`] = useState('');
// outer scope

     // followed by Inner scope has access to variables of the outerscope. 
function ExampleTwo(){
} 

然而,一些差异使得钩子更干净,更适合开发者。

- 在函数组件中,没有this.props this.state。

- 函数组件更简洁,更干净,更容易阅读和编写。

- 语法不同,管理状态、作用域和闭包的方式也不同。

- 例如类中的 componentDidMount 是函数中的 useEffect。

- 我想性能更好,因为代码更少。

这里有两个组件与使用函数和类导出道具时的比较。

 import React, {Component} from 'react'
    export default class Greeting extends Component {
      render() {
        return (
          <View style={{alignItems: 'center'}}>
            <Text style={styles.textSize}>{this.props.name}</Text>
          </View>
        );
      }
    }

和函数组件与道具。

    import React,{useState} from 'react';
    export default function Greeting(props) {
       const [name] = useState(props.name)
        return (
          <View style={{alignItems: 'center'}}>
            <Text style={styles.textSize}>{props.name}</Text>
          </View>
        );
      }
© www.soinside.com 2019 - 2024. All rights reserved.