我有幾個(gè)元件可以擴(kuò)展輸入、按鈕、表格等元素的本機(jī)功能,但我發(fā)現(xiàn)必須在團(tuán)隊(duì)需要時(shí)包含每個(gè)事件處理程序和道具是很乏味的。
我嘗試簡(jiǎn)單地使元件道具類(lèi)型擴(kuò)展本機(jī)道具類(lèi)型,然後使用物件傳播自動(dòng)應(yīng)用所有本機(jī)道具。下一個(gè)問(wèn)題是不支援自訂道具,並且不應(yīng)將其應(yīng)用於原生元素。
為了解決這個(gè)問(wèn)題,我找到的唯一解決方案是複製元件參數(shù)中每個(gè)自訂道具的名稱(chēng),如下所示:{customProp1,customProp2,...nativeProps}。然而,這個(gè)解決方案雖然比必須添加所有原生道具要好得多,但它迫使我複製所有道具,並且我失去了道具。我喜歡用來(lái)區(qū)分 props 和局部變數(shù)的前綴。
有沒(méi)有一個(gè)巧妙的方法可以從自訂道具中過(guò)濾掉原生道具?
我想要實(shí)現(xiàn)的目標(biāo)的範(fàn)例:
import React from 'react' type Props = { color: string, } const Button = ({...props}: Props, {...nativeProps} : React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>) => { return ( <button {...nativeProps} style={{backgroundColor: props.color}} /> ) } export default Button
我目前的最佳解決方案包括複製每個(gè)道具名稱(chēng)並對(duì)其餘道具使用擴(kuò)展運(yùn)算符。
import React from 'react' type CustomProps = { color: string, label: React.ReactNode, name: string, } type Props = CustomProps & Omit<React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, keyof CustomProps>; const Button = ({color, label, ...props}: Props) => { return ( <> {label} <button {...props} style={{backgroundColor: color}} /> </> ) } export default Button
您是否嘗試將 interface
與 extends
一起使用?
import React from 'react'; interface IButtonProps extends React.DetailedHTMLProps, HTMLButtonElement > { color: string; } const Button = ({ color, ...props }: IButtonProps) => { return ; }; export default Button;
否則,您可以嵌套本機(jī)按鈕道具:
import React from "react"; interface IButtonProps { color: string; buttonProps?: React.DetailedHTMLProps, HTMLButtonElement >; } const Button = ({ buttonProps, ...props }: IButtonProps) => { return ; }; const App = () => { return ; }; export default App;