如何为 React TypeScript 组件上的 props 设置默认值?
Posted
技术标签:
【中文标题】如何为 React TypeScript 组件上的 props 设置默认值?【英文标题】:How can I set default values for props on a React TypeScript component? 【发布时间】:2018-07-26 00:28:35 【问题描述】:我使用这种方法来设置默认道具:
TextInputField.defaultProps =
isMultiline: false
但这给了我这个错误:
“typeof TextInputField”类型上不存在属性“defaultProps”。
我错过了什么?
import * as React from "react"
import Text, TextInput, View from "react-native"
import MyButton from "./MyButton"
import colors from "../styles/colors"
import styles from "../styles/form-elements"
interface IComponentState
textInputValue: string
interface IComponentProps
isMultiline: boolean
keyboardType?: any
label?: string
nextButtonText?: string
onSubmit?: () => void
placeholderText?: string
showNextButton?: boolean
export default class TextInputField extends React.Component<IComponentProps, IComponentState>
constructor(props: IComponentProps)
super(props)
public render()
const
keyboardType,
label,
nextButtonText,
onSubmit,
placeholderText,
showNextButton,
isMultiline
= this.props
const textBoxHeight = isMultiline ? 150 : 50
return (
<View>
<Text style=styles.label> this.props.label </Text>
<TextInput
multiline=isMultiline
numberOfLines=5
style=[styles.textInput, height: textBoxHeight ]
placeholder=placeholderText
placeholderTextColor=colors.light_gray
keyboardType=keyboardType
onBlur=showNextButton ? undefined : onSubmit
/>
showNextButton &&
<MyButton
title=nextButtonText
onPress=onSubmit
/>
</View>
)
/**********************
This gives the error:
`Property 'defaultProps' does not exist on type 'typeof TextInputField'.`
**************************/
TextInputField.defaultProps =
isMultiline: false,
nextButtonText: "Next",
onSubmit: () => true,
showNextButton: true,
【问题讨论】:
您好,请查看此链接。 ***.com/questions/37282159/… 【参考方案1】:您也可以这样做。
export default class TextInputField extends React.Component<IComponentProps, IComponentState>
constructor(props: IComponentProps)
super(props)
static defaultProps =
isMultiline: false,
nextButtonText: "Next",
onSubmit: () => true,
showNextButton: true,
public render()
const
keyboardType,
label,
nextButtonText,
onSubmit,
placeholderText,
showNextButton,
isMultiline
= this.props
const textBoxHeight = isMultiline ? 150 : 50
return (
<View>
<Text style=styles.label> this.props.label </Text>
<TextInput
multiline=isMultiline
numberOfLines=5
style=[styles.textInput, height: textBoxHeight ]
placeholder=placeholderText
placeholderTextColor=colors.light_gray
keyboardType=keyboardType
onBlur=showNextButton ? undefined : onSubmit
/>
showNextButton &&
<MyButton
title=nextButtonText
onPress=onSubmit
/>
</View>
)
【讨论】:
以上是关于如何为 React TypeScript 组件上的 props 设置默认值?的主要内容,如果未能解决你的问题,请参考以下文章
如何为无状态 React 组件创建 TypeScript 类型定义?
如何为 TypeScript React 应用程序设置键/值默认状态
如何为 useReducer 键入 state 和 dispatch - typescript 和 react
如何为 React Action Hook Store 定义 Typescript 属性和类型