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/