如何在React TypeScript组件上设置props的默认值?

时间:2018-02-15 09:41:39

标签: reactjs typescript react-native

我使用这种方法来设置默认道具:

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,
}

1 个答案:

答案 0 :(得分:0)

您也可以这样做。

{{1}}