问题
I am running React 16.2.0 and I am using PropTypes 15.6.1. I am using ES6 syntax and Webpack.
I am trying to make PropTypes throw a warning when I pass invalid props, but it doesn't work. This is the code:
SimpleMessage.js
import React from "react"
import PropTypes from "prop-types"
class SimpleMessage extends React.Component {
render() {
return(
<p>{this.props.message}</p>
)
}
}
SimpleMessage.propTypes = {
message: PropTypes.func
}
export default SimpleMessage
index.js
import React from "react"
import ReactDOM from "react-dom"
import SimpleMessage from "./components/SimpleMessage"
window.React = React
ReactDOM.render(
<SimpleMessage message={"Hello World"} />,
document.getElementById("react-container")
)
webpack.config.js
var webpack = require("webpack")
var path = require("path")
process.noDeprecation = true
module.exports = {
entry: "./src/index.js",
output: {
path: path.join(__dirname, 'dist', 'assets'),
filename: "bundle.js",
sourceMapFilename: 'bundle.map'
},
devtool: '#source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
query: {
presets: ['env', 'stage-0', 'react']
}
},
{
test: /\.css$/,
use: ['style-loader','css-loader', {
loader: 'postcss-loader',
options: {
plugins: () => [require('autoprefixer')]
}}]
},
{
test: /\.scss/,
use: ['style-loader','css-loader', {
loader: 'postcss-loader',
options: {
plugins: () => [require('autoprefixer')]
}}, 'sass-loader']
}
]
},
plugins: [
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
warnings: false,
mangle: false
})
]
}
As you might notice I am passing a string ("Hello World") but checking for a function in proptypes. I don't get any errors or warnings by proptypes, and the code runs just fine.
回答1:
Working as expected :
Warning: Failed prop type: Invalid prop
message
of typestring
supplied toSimpleMessage
, expectedfunction
.
Be sure to check your browser console, this is where errors are displayed.
https://codepen.io/anon/pen/paGYjm?editors=1111
Also :
You shouldn’t apply UglifyJsPlugin or DefinePlugin with 'production' value in development because they will hide useful React warnings, and make the builds much slower.
source
回答2:
That's because you've defined propType
as function
, but you're sending it as a string
.
Change the code to message: PropTypes.string
来源:https://stackoverflow.com/questions/49050730/proptypes-doesnt-work-in-react