问题
React Navigation's introduction page suggests the use of the following destructuring assignment:
const { navigate } = this.props.navigation;
However, when I implemented React Navigation in my App, ESLint is complaining about this line describing these both errors:
'navigation' is missing in props validation (react/prop-types)
'navigation.navigation' is missing in props validation (react/prop-types)
Even though the app seems to be working as intended, how would it be possible to remove these error lines?
回答1:
One option is to add the propTypes
prop to the component.
Example
LoginScreen.propTypes = {
navigation: PropTypes.object.isRequired,
};
Another option is to disable eslint for that page and rule. More info here
Rule Options
This rule can take one argument to ignore some specific props during validation.
... "react/prop-types": [<enabled>, { ignore: <ignore>, customValidators: <customValidator> }] ...
回答2:
React.PropTypes
has moved into the prop-types
package since React v15.5 (see Typechecking with PropTypes).
It should be used instead of importing from react-native
(the package can be added into the project via npm install --save prop-types
or yarn add prop-types
).
And the example code complying with "Component should be written as a pure function" rule as follows:
// In addition to other imports:
import PropTypes from 'prop-types';
const LoginScreen = ({ navigation }) => (
<View>
<Button
title="Login"
onPress={() => navigation.navigate('MainScreen')}
/>
</View>
);
LoginScreen.propTypes = {
navigation: PropTypes.shape({
navigate: PropTypes.func.isRequired,
}).isRequired,
};
回答3:
Solution today (since object Proptype isn't accepted by default anymore):
export default class LoginScreen extends Component {
static propTypes = {
navigation: PropTypes.shape({
navigate: PropTypes.func.isRequired,
}).isRequired,
}
}
回答4:
When Project needs navigation to almost all componenets. We can also silence the linting for that specific prop.
By adding the following in the eslint configuration:
"rules": {
"react/prop-types": ["error", { "ignore": ["navigation"] }]
}
回答5:
In case of navigation in ES5 use something like this:
LoginScreen.propTypes = {
navigation: PropTypes.object.isRequired,
};
in ES6 use this:
static PropTypes = {
navigation: PropTypes.object.isRequired,
};
and
import PropTypes from 'prop-types';
来源:https://stackoverflow.com/questions/46868188/react-navigation-navigation-is-missing-in-props-validation