javascript - 我想将下面的 for 循环转换为 array.map() 但不确定如何

标签 javascript arrays reactjs

OtpInput 是另一个组件,OTPLength 是从父组件获取的属性,是必需的。

{
    const otp = getOtpValue()
    const inputs = []

    for (let index = 0; index < OTPLength; index++) {
      inputs.push(
        <Input
          key={index}
          focus={activeInput === index}
          value={otp[index]}
          onChange={handleOnChange}
          onKeyDown={handleOnKeyDown}
          onInput={handelOnInput}
          onInputFocus={onInputFocus}
          index={index}
          secure={secure}
          invalid={invalid}
          autoFocus={autoFocus}
        />
      )
    }

    return inputs
}

尝试并更改了以下方式,但我只得到一个输入,而不是作为 Prop 传递给 OTPLength 的值,然后用于创建基于 OTPLength 的新数组。

const renderInputs = useMemo(() => {
    const otp = getOtpValue()
    const inputs = new Array(OTPLength)
    return [...inputs].map((_,index) =>
            <Input
                key={index}
                focus={activeInput === index}
                value={otp[index]}
                onChange={handleOnChange}
                onKeyDown={handleOnKeyDown}
                onInput={handelOnInput}
                onInputFocus={onInputFocus}
                index={index}
                secure={secure}
                invalid={invalid}
                autoFocus={autoFocus}
              />
            )
  }, [
    getOtpValue,
    OTPLength,
    activeInput,
    handleOnChange,
    handleOnKeyDown,
    handelOnInput,
    onInputFocus,
    autoFocus,
    invalid,
    secure
  ])

最佳答案

简单地遍历一个Array()map()second参数指的是当前指数

    const myArray = [...new Array(OTPLength)].map((obj, i)=> (
      <Input
        key={index}
        focus={activeInput === i}
        value={otp[i]}
        onChange={handleOnChange}
        onKeyDown={handleOnKeyDown}
        onInput={handelOnInput}
        onInputFocus={onInputFocus}
        index={index}
        secure={secure}
        invalid={invalid}
         autoFocus={autoFocus}
       />
));

关于javascript - 我想将下面的 for 循环转换为 array.map() 但不确定如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58872096/

相关文章:

javascript - Web Audio API - 录制到 MP3?

php - 你能在 PHP 中使用全局方法吗?

arrays - Go语言中的结构体数组

PHP & MySQL : Show SUM of Something, 按不同类别分类

javascript - 功能 Prop 是否需要 'noop' [lodash] 默认参数?

javascript - 哪些组件正在添加情感 css 全局样式

javascript - 如何使用 "Select All"复选框传递所有对象?

ios - 尝试从 Swift 中的 UI 将值添加到数组索引

javascript - 如果用户导航到其他路线, Electron reactjs 应用程序在重新加载后显示空页面

javascript - 遵循 React + Node.js 博客教程时出现语法错误 "Unexpected token"