在 React 中的函数内部声明函数 [英] Declaring function inside function in React

查看:111
本文介绍了在 React 中的函数内部声明函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚遇到了一个 React 代码,我不确定它是否是一个好方法.这是该代码的示例实现.

class App 扩展 React.Component {renderMessage = () =>{函数 getMessage() {回复你好"}函数 getName() {返回维杰"}返回 (<h1>{getMessage()} {getName()} !!!</h1>)}使成为() {返回 (<div>{this.renderMessage()}

)}}

这里我们在render中调用一个函数renderMessage.在 renderMessage 中有两个内部函数,它们只在 renderMessage 内部调用.我现在的问题是:-

  • 这是一个好方法吗?它不会在每次 render 调用时重新声明方法 getNamegetMessage.
  • 如果我创建 getNamegetMessage 类方法并在 renderMessage 中调用它们,这会是一种改进吗?

谢谢:)

解决方案

这是一个好方法吗?它不会在每次渲染调用时重新声明方法 getName 和 getMessage

绝对不是一个好方法.因为 JavaScript 要么具有功能性,要么具有块或全局作用域.您在此范围内定义的任何内容都将仅是此范围的一部分.在您的情况下,这些函数 getMessagegetName 将成为 renderMessage 的一部分是功能范围.

每次调用时,都会定义新函数,而不是重用以前定义的函数.

<块引用>

如果我创建 getName 和 getMessage 类方法并在 renderMessage 中调用它们会有所改进吗?

视情况而定.如果此函数需要访问任何组件属性或方法,则应将其放置在组件中,或者如果这只是实用程序函数,则将其放置在与组件分开的辅助库中.当然,这会有所作为.

I just came across a React code and I'm not sure whether it's is a good way to do it or not. This is a sample implementation of that code.

class App extends React.Component {
  renderMessage = () => {
    function getMessage() {
      return "Hello"
    } 
    function getName() {
      return "Vijay"
    }
    return (
      <h1>{getMessage()} {getName()} !!!</h1>
    )
  }
  render() {
    return (
      <div>
        {this.renderMessage()}
      </div>
    )
  }
}

Here we are calling a function renderMessage inside render. In renderMessage there are two inner functions which are called inside renderMessage only. My question now are:-

  • Is it a good approach to do? Won't it redeclare method getName and getMessage at every render call.
  • If I make getName and getMessage class methods and call them inside renderMessage would it be an improvment?

Thanks :)

解决方案

Is it a good approach to do? Won't it redeclare method getName and getMessage at every render call

Definitely not a good approach. As JavaScript is either having functional or block or global scope. Whatever you defining at this scope will be part of this scope only.In your case, these function getMessage and getName will be part of renderMessage which is functional scope.

At every call, new functions are getting defined instead reusing previously defined.

If I make getName and getMessage class methods and call them inside renderMessage would it be an improvement?

Depend. If this function need an access to any component properties or method then you should place it inside the component or If this is only utility function then place it inside helper library separate from component. Surely, this will make difference.

这篇关于在 React 中的函数内部声明函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆