【问题标题】:Concatenating a string and a variable within curly braces在花括号内连接字符串和变量
【发布时间】:2019-07-05 16:23:52
【问题描述】:

如何在{} 中连接字符串和变量?例如。 onClick={this."social"+key}:

                    <Button
                    onClick={this.'social'+key}
                      color="transparent"
                      justIcon
                      key={key}
                      className={classes.customButtonClass}
                    >

【问题讨论】:

  • 你能解释一下点击处理程序中连接的意义何在?
  • 这是您要连接的函数名称吗?
  • 我已经制作了数组,它与参数键映射,我可以从中创建函数
  • 是的,我将使用该名称构建函数
  • 您也可以提供替代方案

标签: javascript reactjs typescript


【解决方案1】:

您可以将这些函数存储在一个数组中,并可以在onClick 中使用该数组,

render() {
    const fns = [this.social0, this.social1, this.social2, this.social3]
    return (
      <div>
        {buttons.map((btn, key) => {
          return (
            <button onClick={fns[key]} key={key}>
              {btn}
            </button>
          )
        })}
      </div>
    )
  }

Demo

【讨论】:

    猜你喜欢
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    • 2014-09-29
    • 1970-01-01
    相关资源
    最近更新 更多