【问题标题】:How can I concatenate index to a function in Reactjs elements如何将索引连接到 Reactjs 元素中的函数
【发布时间】:2020-11-19 22:24:36
【问题描述】:

我有很多编号方法,我想使用循环为输入元素制作单个渲染。

这是我的代码:

{new Array(6).fill(0).map((inp, index) =>(
                        <input
                            key = {index}
                            className="input_otp"
                            theme={{ color }}
                            ref = {inputRefs[index]}
                            onChange={handleChange}
                            onKeyDown={onKeyOTP2}
                            onFocus={onFocusOTP2}
                            type="tel"
                            maxlength="1"
                            value={state['otp'+ (index + 1)]}
                            name={'otp'+ (index + 1)}
                        />
                        ))
                    }

现在我想为这些事件方法添加索引以使其动态onKeyOTP+(index+1) 变为

onKeyDown={onKeyOTP2}

就像我对其他属性所做的那样。需要这方面的帮助。

【问题讨论】:

  • 为什么没有一个接受索引作为参数的通用方法?
  • 你是说组件包含像onKeyOTP1onKeyOTP2onKeyOTP3等硬编码方法?
  • 可以做到,但这需要很多改变,我想知道这种方式是否可行。
  • @ChrisG 是的,对
  • 这看起来是一个非常糟糕的设计。我不知道有什么方法可以实现这样的功能——唯一的选择是创建一个包装开关函数,它会根据收到的索引返回适当的函数。

标签: javascript reactjs ecmascript-6 jsx ecmascript-5


【解决方案1】:

你可以用this绑定函数。

{new Array(6).fill(0).map((inp, index)=>(
                    <input
                        key = {index}
                        className="input_otp"
                        theme={{ color }}
                        ref = {inputRefs[index]}
                        onChange={handleChange}
                        onKeyDown={this[`onKeyOTP${index + 1}`]}
                        onFocus={onFocusOTP2}
                        type="tel"
                        maxlength="1"
                        value={state['otp'+ (index + 1)]}
                        name={'otp'+ (index + 1)}
                    />
                    ))
                }

【讨论】:

    【解决方案2】:

     this.abc1 = () => {
      return '1';
    }
    
    this.abc2 = () => {
      return '2'
    }
    
    for(let i = 1; i< 3; i++){  
      let j = this[`abc${i}`];
      console.log("j is", j());
    }

    类似的东西

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-21
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多