Const = () => vs Class Functions function name() {} in React Native

Muh*_*sar 5 components reactjs react-native

I'm new to react native, I'm bit confused about components.

As I created first react native app I saw App.js the components in App.js created as per following code:

export default function App() {
 ...
}
Run Code Online (Sandbox Code Playgroud)

and as I saw tutorials many people almost all people making components as per following code:

const FirstComponents = () => {
  ...
}
Run Code Online (Sandbox Code Playgroud)

I'm also confuse about function components and class based components which created as per following code:

export default class FirstComponents extends Components(){
 ...
}
Run Code Online (Sandbox Code Playgroud)

What is the difference between function and class base components?

Please provide me answer with examples. Your time will be appreciated.

oct*_*bus 6

在 javascript 中,有多种方法可以创建一个函数。例如:

function myFunction () {
//some action
}
const myFunction = () => {
//some action
}
Run Code Online (Sandbox Code Playgroud)

这两个是函数,做同样的事情。

现在您的问题的第二部分是“功能组件和基于类的组件之间有什么区别?”

过去用于控制您state和生命周期方法(ComponentDidMount 等...)的基于类的组件。如果您不在state组件或生命周期方法中使用,您将使用基于函数的组件。基本上如果你有一个只有一些 UI 东西的小组件,最好使用功能组件。然而,随着 React 16.8 版,React 团队引入了hooks.

Hooks 为您的状态和组件生命周期方法等提供了相同的概念。使用钩子你可以控制你的组件,即使它们是功能组件。


Jai*_*Jai 3

前两个片段在声明方面相似。两者都是功能组件。这些与基于类的组件不同。有几个区别:

  1. 挂钩只能在功能组件中使用,基于类则不能。
  2. 构造函数用于this在类组件中进行初始化,但在函数中则不需要this
  3. 生命周期钩子在功能组件中不可用,它们是类组件的一部分。
  4. 您可以将useEffecthook 用于生命周期钩子,例如componentDidMount.

举一个简短的例子:

function App(){

    const [count, setCount] = useState('');

}
Run Code Online (Sandbox Code Playgroud)

上面的例子"count"是组件的本地状态属性,setCount是更新状态的方法。

class App extends React.Component{
   constructor(props){
      super(props);
      this.state = { count: 0 };
      this.increaseCount = this.increaseCount.bind(this);
   }

   increaseCount(){
      this.setState({count: this.count+1});
   }
   // lifecycle methods like componentDidMount, componentDidUpdate etc.
   render(){
      return(
        <button onClick={this.increaseCounter}>INCR</button>
      );
   }

}
Run Code Online (Sandbox Code Playgroud)

在此类组件中,您可以看到状态是在构造函数中定义的,并使用该setState方法进行更新。

实时示例会太多,无法添加,因此我建议您使用简单的示例来掌握概念。