undefined 不是对象(正在计算 _react.default.PropTypes.func)

undefined is not an object (evaluating _react.default.PropTypes.func)

一周以来我一直在参考一个包含 8 个部分的教程,代码库依赖于第 1 部分。在后面的部分中,我根据教程创建了一个 ColorForm.js 文件,其中包括下面的代码。当我定义了 ColorForm.PropTypes 例如

ColorForm.propTypes = {
    onNewColor: React.PropTypes.func.isRequired
}

应用程序抛出错误,undefined 不是对象(正在评估 _react.default.PropTypes.func)

参考各种 post 我开始知道我必须安装 'prop-types',即使我收到上述错误。谁能帮我解决这个问题。提前致谢。

ColorForm.js

import React, {Component} from 'react'
import {
    View,
    Text,
    StyleSheet,
    TextInput
} from 'react-native'

export default class ColorForm extends Component {
    constructor() {
        super()
        this.state = {
            txtColor: ''
        }

        this.props.onNewColor(this.state.txtColor.toLowerCase())
        this.submit = this.submit.bind(this)
    }

    submit() {
        this.setState({txtColor: ''})
    }

    render() {
        return(
            <View style = {styles.container}>
                <TextInput 
                    style = {styles.txtInput}
                    placeholder = "Enter a color..."
                    onChangeText={(txtColor) => this.setState({txtColor})}
                    value  = {this.state.txtColor}
                />
                <Text style = {styles.button} onPress={this.submit}>Add</Text>
            </View>
        )
    }
}

ColorForm.propTypes = {
    onNewColor: React.PropTypes.func.isRequired
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-around',
        backgroundColor: 'lightgrey',
        height: 70
    },
    txtInput: {
        flex: 1,
        margin: 5,
        padding: 5,
        borderWidth: 2,
        fontSize: 20,
        borderRadius: 5,
        backgroundColor: 'snow'
    },
    button: {
        backgroundColor: 'darkblue',
        margin: 5,
        padding: 5,
        alignItems: 'center',
        justifyContent: 'center',
        color: 'white',
        fontSize: 20
    }
})

代替 React.PropTypes 直接使用 PropTypes。

第 1 步:import PropTypes from 'prop-types';

 onNewColor: PropTypes.func.isRequired 

第 2 步。

 constructor() {
        super()
        this.state = {
            txtColor: ''
        }

        this.props.onNewColor = this.onNewColor.bind(this)
        this.submit = this.submit.bind(this)
    }

    onNewColor(textColor) => {
      return textColor.toLowerCase()
    }

第 3 步:

  <TextInput 
      style = {styles.txtInput}
      placeholder = "Enter a color..."
      onChangeText={(txtColor) => this.setState({txtColor})}
      value  = {this.props.onNewColor(this.state.txtColor)}
  />