React Native子组件更新父状态报错:'changeModalVisibility'缺失props校验
解决React Native里「'changeModalVisibility' is missing in props validation」报错
嘿,这个报错其实是ESLint的react/prop-types规则在给你提个醒:你的子组件接收了changeModalVisibility这个props,但没明确声明它的类型,ESLint担心你传错类型或者用到不存在的props,所以才跳出来提示你。下面给你几种靠谱的解决办法:
方案1:用PropTypes给props做类型声明(最常用的常规操作)
React Native自带了PropTypes库,不需要额外安装,直接用就行。我们只需要在子组件里给changeModalVisibility标注清楚它是个必填的函数类型。
修改后的子组件代码:
import React, { Component } from 'react'; import { TouchableHighlight, Text } from 'react-native'; import PropTypes from 'prop-types'; // 先把PropTypes导入进来 class ChildClass extends Component { // 用箭头函数绑定this,避免调用时this指向乱掉 closeButtonTapped = () => { this.props.changeModalVisibility(false); // 这里记得传false哦,你之前的代码里漏了参数 }; render() { return ( <TouchableHighlight underlayColor="none" onPress={this.closeButtonTapped} style={{ alignItems: 'center', justifyContent: 'center' }} > <Text style={{ color: 'white', marginTop: 10, marginLeft: 20, fontWeight: '600', fontSize: 18 }}>Close</Text> </TouchableHighlight> ); } } // 关键步骤:给子组件添加props验证 ChildClass.propTypes = { changeModalVisibility: PropTypes.func.isRequired, // 明确告诉ESLint,这是个必须传的函数 }; export default ChildClass;
另外顺便提一句,你父组件里的changeModalVisibility函数有个小bug:this.setState({ isModalVisible: visible });里的visible应该是你接收的参数bool,改成下面这样才对:
changeModalVisibility = (bool) => { this.setState({ isModalVisible: bool }); }
方案2:如果用函数式组件+TypeScript
要是你的项目用了TypeScript,那直接用接口定义props类型就更爽了,还能享受到TS的类型检查:
import React from 'react'; import { TouchableHighlight, Text } from 'react-native'; // 先定义好props的类型接口 interface ChildProps { changeModalVisibility: (visible: boolean) => void; } const ChildClass: React.FC<ChildProps> = (props) => { const closeButtonTapped = () => { props.changeModalVisibility(false); }; return ( <TouchableHighlight underlayColor="none" onPress={closeButtonTapped} style={{ alignItems: 'center', justifyContent: 'center' }} > <Text style={{ color: 'white', marginTop: 10, marginLeft: 20, fontWeight: '600', fontSize: 18 }}>Close</Text> </TouchableHighlight> ); }; export default ChildClass;
方案3:临时禁用ESLint规则(不推荐)
如果你只是想快速跳过这个提示,不想做类型声明,可以在子组件的最顶部加个注释:
/* eslint-disable react/prop-types */
不过真心不建议长期这么搞,props验证能帮你提前发现很多类型错误,比如不小心把函数传成了字符串,能有效避免运行时的bug。
最后再补个小提醒:你的子组件里的closeButtonTapped如果是普通函数的话,一定要注意this的指向问题,用箭头函数或者在构造函数里绑定this,不然调用的时候可能会出现this.props找不到的情况哦~
内容的提问来源于stack exchange,提问作者iOSDev
相关产品推荐
相关产品推荐

