reactjs - React Native 组件中的函数(函数与 const 函数)

标签 reactjs function react-native function-declaration

这可能非常简单,但我不太清楚如何搜索答案。

我刚刚注意到我的 React Native 组件中有一些函数,有时我用 const 声明,而另一些则不声明,而且似乎没有区别。

像这样

const MyComponent = (props) => {
 
     const myFunction = () => {
        console.log("Hello world");
     }
     return(
         <TouchableOpacity onPress={myFunction}>
            ...somestuff
         </TouchableOpacity>
     )
}

const MyComponent = (props) => {
 
     myFunction = () => {
        console.log("Hello world");
     }
     return(
         <TouchableOpacity onPress={myFunction}>
            ...somestuff
         </TouchableOpacity>
     )
}

就输出而言,我找不到它们之间有什么不同。这只是编译器保存了我的 a*s 还是它们之间实际上有区别?

最佳答案

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

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

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

关于reactjs - React Native 组件中的函数(函数与 const 函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63058927/

相关文章:

javascript - 将纯文本 react 为 html 代码

function - 我可以将任意函数传递给 Scala 中的另一个函数吗?

javascript - 无法在 componentDidMount React Native 中发送请求

android - android上左键和标题之间的 react 导航空间

javascript - 使用material-ui中的mixins来自定义React中的组件

reactjs - 找不到模块 : Error: Can't resolve '@material-ui/core/styles' (when deploying to heroku)

reactjs - 使用 React Router 以编程方式导航,无需重复路径

function - 在postgresql函数中循环遍历数据库

javascript - 将循环转换为递归函数

ios - 切换到另一个应用程序/主屏幕时如何完全关闭 iOS 应用程序(删除它使用的 RAM)