You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 11:36:08