Reactjs React本机组件中的函数(函数与常量函数)

Reactjs React本机组件中的函数(函数与常量函数),reactjs,function,react-native,function-declaration,Reactjs,Function,React Native,Function Declaration,这可能非常简单,但我不知道如何搜索答案 我刚刚注意到,我的react原生组件中有函数,有时我用const声明,而其他组件则没有,这似乎没有什么区别 像这样 const MyComponent = (props) => { const myFunction = () => { console.log("Hello world"); } return( <TouchableOpacity onP

这可能非常简单,但我不知道如何搜索答案

我刚刚注意到,我的react原生组件中有函数,有时我用const声明,而其他组件则没有,这似乎没有什么区别

像这样

const MyComponent = (props) => {
 
     const myFunction = () => {
        console.log("Hello world");
     }
     return(
         <TouchableOpacity onPress={myFunction}>
            ...somestuff
         </TouchableOpacity>
     )
}
const MyComponent=(道具)=>{
常量myFunction=()=>{
log(“你好世界”);
}
返回(
…一些东西
)
}

const MyComponent=(道具)=>{
myFunction=()=>{
log(“你好世界”);
}
返回(
…一些东西
)
}

我看不出他们在产量方面有什么不同。这仅仅是编译器保存了我的a*s,还是它们之间确实有区别?

我认为在react native中,it并不重要,因为它的生命周期。但在普通javascript中,它在提升方面有所不同。如果没有常量,则可以调用尚未声明的函数:

doTheThing();


function doTheThing() {
   console.log(`This is awesome number ${getAwesome()}`)
}

function getAwesome() {
  return (+((Math.random() * 10000).toString().split('.')[0]))
}
使用Const/let它不允许您这样做:

 const tryDoTheThing = () => {
    console.log(`This is me trying to be awesome ${getAwesome()}`)
 }


 // "getAwesome is not defined", because it is referenced too early
 tryDoTheThing() // comment to see the rest work


 const getAwesome = () => (+((Math.random() * 10000).toString().split('.')[0]))


 const doTheThing = () => {
   console.log(`This is awesome! ${getAwesome()}`)
 }

 doTheThing() // prints

使用
函数
会将其声明放在当前作用域的顶部(当前脚本或当前函数的顶部)。

Javascript不会阻止您使用未声明的变量

x=10;//这完全可以,因为它将添加到全局范围中

为了避免这样做,通常使用
use strict

"use strict";
x = 10;       // This will cause an error because x is not declared

因为我不知道,所以我将把它作为一个注释,但我猜编译器正在拯救你——我这么说是因为我的linter抱怨如果我不在这样的函数上使用const/let。同意,第二个肯定是不正确的语法。
"use strict";
x = 10;       // This will cause an error because x is not declared