我最近開始使用 react with typescript ,當我使用可選/默認值解構 props 時,似乎發生了一些奇怪的事情。例如用這個函式生成一個隨機 id:
interface GenKeyIdProps {
length?: number;
}
/**
* Generate a random id (mainly for use with rendering lists of components.
* genKeyId convert Math.random to base 36 (numbers letters), and grab the first ${lenght} characters after the decimal.
* @param length (optional) specify how many characters the id should be. default is 5.
* @returns a string with number and letters of specified length.
*/
export const genKeyId = ({ length = 5 }: GenKeyIdProps) => Math.random().toString(36).substr(2, length);
問題是當我嘗試呼叫它時:
import { genKeyId } from '../../../helpers';
interface TextWrapperProps {
textLines: string[];
}
const TextWrapper = ({ textLines }: TextWrapperProps) => {
return textLines.map(line => (<div key={genKeyId()}>{line}</div>));
};
export default TextWrapper;
如果我沒有將至少一個空物件傳遞給 genKeyId,我會收到以下錯誤:預期 1 個引數,但得到 0.ts(2554)。
為什么我需要傳遞一個空物件?我的 GenKeyIdProps 介面是否指定道具需要成為物件的一部分?我對此有些困惑。
uj5u.com熱心網友回復:
我的 GenKeyIdProps 介面是否指定道具需要成為物件的一部分?
是的,你已經定義GenKeyIdProps為一個物件。所有interface定義都是物件。你GenKeyIdProps的大致相當于:
type GenKeyIdProps = {
length?: number;
};
也就是說,具有lengthtype可選屬性的物件number。
genKeyId不過,沒有必要接受一個物件;它不是一個組件函式,它只是一個效用函式。您可以length通過洗掉解構將其定義為直接接受:
export const genKeyId = (length = 5) => Math.random().toString(36).substr(2, length);
或者,如果您確實希望它接受一個物件,但希望它能夠在沒有物件的情況下被呼叫,則可以默認您正在解構的引數:
export const genKeyId = ({ length = 5 }: GenKeyIdProps = {}) => Math.random().toString(36).substr(2, length);
// ???????????????????????????????????????????????????^^^^^
現在您可以genKeyId使用具有length;的物件呼叫A) 。B) 一個沒有length;的物件 和 C) 根本沒有爭論。
是否要getKeyId接受數字或具有length屬性的物件取決于您。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/322062.html
下一篇:如何匯入不同名稱的MUI組件?
