3 回答

TA貢獻1785條經驗 獲得超8個贊
簡單地遍歷一個空的 Array(),第二個參數是map()指當前索引
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}
/>
));

TA貢獻1847條經驗 獲得超7個贊
你甚至不需要map(),你可以簡單地做:
const inputs = Array.from({length: OTPLength}, (_,i) =>
<Input
key={i}
focus={activeInput == i}
/* the rest of your props */
/>
)
或者,如果您仍然喜歡map():
const inputs = [...Array(OTPLength)].map((_,i) =>
<Input
key={i}
focus={activeInput == i}
/* the rest of your props */
/>
)

TA貢獻1812條經驗 獲得超5個贊
這應該有效,
const renderInputs = useMemo(() => {
const otp = getOtpValue()
const inputs = new Array(OTPLength)
let ret = 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}
/>
);
return ret;
}, [
getOtpValue,
OTPLength,
activeInput,
handleOnChange,
handleOnKeyDown,
handelOnInput,
onInputFocus,
autoFocus,
invalid,
secure
])
添加回答
舉報