React Native中作为Props传递的函数失效问题排查
React Native函数Props传递失效问题解决
问题描述
在React Native开发中,调用自定义SearchBar组件时,从StoreScreen传递的handleOnFocus函数始终无法被正确接收,触发onFocus事件时报错:TypeError: handleOnFocus is not a function。尝试过直接传入匿名函数、解构Props等方式均无效。
核心原因
SearchBar组件的参数接收方式错误:React组件的Props是以单个对象的形式传入的,而非独立的参数列表。原代码中将Props拆分为多个独立参数,导致传递的handleOnFocus无法被正确匹配到对应的参数位置,最终拿到的是undefined。
解决方案
将SearchBar组件改为接收单个Props对象,通过解构或直接访问对象属性的方式获取所需参数。
修改后的SearchBar组件代码
import { View, TextInput, StyleSheet } from "react-native"; import { Ionicons } from "@expo/vector-icons"; /** * Generic bar Component * @param {object} props * @param {boolean} props.border shows border if true * @param {number} props.iconSize size of the icon of the search bar * @param {StyleSheet.NamedStyles} props.addStyles add styles to the search bar * @param {string} props.placeholder string that is shown in the search bar * @param {Function} props.handleOnFocus function for onFocus() * @param {Function} props.onChangeText function for onChangeText() * @param {Function} props.onBlur function for onBlur() * @returns Generic SearchBar component */ export default function SearchBar(props) { // 解构Props,设置默认值 const { border = false, iconSize = 20, addStyles, placeholder = "search", handleOnFocus, onChangeText, onBlur } = props; return ( <View style={[Styles.searchbarView, addStyles]}> <Ionicons name="search" size={iconSize} /> <TextInput style={{ flex: 1, marginLeft: 5, justifyContent: "center", fontSize: 16, }} placeholder={placeholder} onChangeText={onChangeText} onFocus={() => { if (handleOnFocus) handleOnFocus(); // 增加判断避免无函数时报错 }} onBlur={onBlur} /> </View> ); } const Styles = StyleSheet.create({ searchbarView: { height: 35, justifyContent: "flex-start", alignItems: "center", flexDirection: "row", marginTop: 30, borderColor: "#1ACE2B", borderWidth: 1, borderRadius: 7, paddingHorizontal: 10, marginHorizontal: 20, }, });
说明
- 组件参数改为接收单个
props对象,符合React组件的标准写法 - 通过对象解构获取需要的属性,并保留原有的默认值设置
- 在调用
handleOnFocus前增加存在性判断,避免因未传递函数导致额外报错 StoreScreen中的调用代码无需修改,原写法<SearchBar border={true} handleOnFocus={consl} />是正确的
Expo环境版本
{ "expo": { "name": "Program", "slug": "Program", "version": "1.0.0", "orientation": "portrait", "icon": "./assets/icon.png", "userInterfaceStyle": "light", "splash": { "image": "./assets/splash.png", "resizeMode": "contain", "backgroundColor": "#ffffff" }, "updates": { "fallbackToCacheTimeout": 0 }, "assetBundlePatterns": [ "**/*" ], "ios": { "supportsTablet": true }, "android": { "adaptiveIcon": { "foregroundImage": "./assets/adaptive-icon.png", "backgroundColor": "#FFFFFF" } }, "web": { "favicon": "./assets/favicon.png" } } }
内容的提问来源于stack exchange,提问作者Aissa Rouk
相关产品推荐
相关产品推荐

