在JS中嵌套函数 [英] Nesting Functions in JS

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

问题描述

我试图理解reactjs中的一些概念,但我无法理解函数的嵌套。我创建了以下示例来调查我的担忧。

I am trying to understand some concepts in reactjs, but I'm unable to understand nesting of functions. I created the below example for investigating my concern.

在下面的例子中,我正在渲染一些内容,其中的值来自一系列嵌套函数。但是,我收到错误Uncaught TypeError:无法读取未定义的属性'renderInnerContent'。你能帮我理解发生了什么以及如何解决这个问题吗?我的主要动机是了解如何将事物抽象为不同的功能。

In the below example, I'm rendering some content the value of which is coming from a series of nested functions. However, I get the error "Uncaught TypeError: Cannot read property 'renderInnerContent' of undefined". Can you please help me understand what's happening and how to resolve this problem? My primary motive is to understand how to abstract things into different functions.

import React, { Component } from 'react';

export default class MyComponent extends Component {
  renderInnerContent() {
    return (
      <div>Innercontent</div>
    )
  }

  renderContent() {
    let data = ["a","b","c"];
    const displaydata = data.map(function(point){
      return (
        <div key={point}>{this.renderInnerContent()}</div>
      )
    });
    return (
      <div>{displaydata}</div>
    )
  }

  render() {
    return (
      <div>{this.renderContent()}</div>
    )
  }
}


推荐答案

未在该函数的上下文中定义:

this is not defined in that function's context:

function(point){
  return (
    <div key={point}>{this.renderInnerContent()}</div>
  )
}

因为它是一个新功能。
您有不同的选项将传递给该函数:

Because it is a new function. You have different options to pass this to that function:

1- 脂肪箭头功能

renderContent() {
   let data = ["a","b","c"];
   const displaydata = data.map((point) => {
      return (
        <div key={point}>{this.renderInnerContent()}</div>
       )
   });
   return (
      <div>{displaydata}</div>
   )
}

2-定义一个变量:

renderContent() {
   let data = ["a","b","c"];
   let _this = this;
   const displaydata = data.map(function(point){
      return (
        <div key={point}>{_this.renderInnerContent()}</div>
       )
   });
   return (
      <div>{displaydata}</div>
   )
}

3-使用 bind

3- Use bind:

renderContent() {
   let data = ["a","b","c"];
   const displaydata = data.map(function(point){
      return (
        <div key={point}>{this.renderInnerContent()}</div>
       )
   }.bind(this));
   return (
      <div>{displaydata}</div>
   )
}

PS:不确定其中任何一个在React中都不起作用。

PS: Not sure any of these is not working in React.

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

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