TypeScript开发React Native自定义组件如何继承原生组件全部Props属性
解决方案
你只需要让你的自定义组件Props接口继承React Native内置的TextInputProps类型,同时把未显式解构的剩余属性透传给原生TextInput即可,具体实现如下:
第一步:导入内置类型并修改自定义接口
import { TextInput, TextInputProps, ViewStyle } from 'react-native' // 用extends继承所有TextInput原生属性,如果你自定义的属性和原生属性重名,还可以用Omit排除重名属性 export interface CustomTextInputI extends TextInputProps { customPlaceHolder: string // 如果你需要重写原生style的类型,可以这么写: // export interface CustomTextInputI extends Omit<TextInputProps, 'style'> { style: ViewStyle // 其他自定义属性 }
第二步:修改组件实现,透传剩余属性
export const CustomTextInput = (props: CustomTextInputI) => { // 显式解构自定义属性,剩下的所有原生属性都放rest里 const { customPlaceHolder, style, ...rest } = props return ( <TextInput style={style} placeholder={customPlaceHolder} {/* 把所有原生属性透传给原生组件 */} {...rest} /> ) }
修改完成后你就可以正常传入secureTextEntry等所有原生TextInput支持的属性了,TypeScript不会再报错。
内容的提问来源于stack exchange,提问作者CODEforDREAM
相关产品推荐
相关产品推荐

