【问题标题】:Passing variables into arrow function将变量传递给箭头函数
【发布时间】:2021-07-29 23:27:46
【问题描述】:

我认为我对箭头函数的编码问题存在误解。我下面的代码应该将返回的 jsx 存储在变量“header”中。但它不起作用。是不是我传入的参数不正确?

switch (props.category) {
    case 'White':
      heading = 'White Advantages';
      break;
    case 'Black':
      heading = 'Black Advantages';
      break;
    case 'Neutral':
      heading = 'Neutral';
      break;
    default:
      break;
  }

  let header = (heading, advisorTags) => {
    if (advisorTags.length > 0) {
      return (
        <Typography variant="h6" component="h6" style={{ fontSize: 16 }}>
          {heading}
        </Typography>
      );
    }
  };

【问题讨论】:

  • 标头是反应组件吗? switch 语句是如何出现的?
  • header 只是一个变量。你可以看到我让 header = ... switch 语句设置变量“heading”,然后我在 header 函数的参数中使用它。

标签: reactjs


【解决方案1】:

不,目前header 是一个接受 2 个输入的函数:headingadvisorTags

如果您想将返回的 jsx 存储在变量“header”中,您必须编写如下内容:

const getMyHeader = (heading, advisorTags) => {
    if (advisorTags.length > 0) {
      return (
        <Typography variant="h6" component="h6" style={{ fontSize: 16 }}>
          {heading}
        </Typography>
      );
    }
  };

let header = getMyHeader(heading, advisorTags);

【讨论】:

  • 对,这是有道理的。在 let 标头中,您传入了值标题和 advisorTags,而在 const getMyHeader 中,它们不是值,而是您传入的数据的标签。我正在尝试,但是当我控制台日志标头时,我得到了这个从$$typeof: Symbol(react.element) 开始的奇怪输出,但我期待的是 文本。你觉得我哪里做错了?
  • 没关系,我现在可以正常使用了。我现在知道变量中存储的是 jsx 而不是 html,因此控制台日志看起来会有所不同。
猜你喜欢
  • 2017-08-21
  • 2018-06-26
  • 2018-12-13
  • 2020-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多