React Native扩展Button组件后event.currentTarget.props为何为undefined?
问题原因与解决方案
React Native 的 Button 是原生封装组件,它的 onPress 回调和 Web 端 React 的事件机制完全不同——不会传递包含组件 props 的事件对象。你拿到的 GestureResponderEvent 仅包含触摸相关的原生事件信息,根本不存在 currentTarget.props 这个属性,这和你是否正确扩展组件无关,是 RN 原生组件的事件设计逻辑导致的。
另外你写的 MyButton 只是简单透传 props 给原生 Button,但原生 Button 不会把自定义的 signature 属性附加到事件里,所以你在父组件的 _onPressButton 里根本拿不到这个值。
下面是几种可行的解决办法:
方案1:封装MyButton,内部传递signature参数
修改你的 MyButton 组件,在内部拦截点击事件,把 signature 作为参数传给父组件的回调:
import React from 'react'; import { Button, ButtonProps, View, StyleSheet, Alert } from 'react-native'; interface MyButtonProps extends ButtonProps { signature: string; onPress: (signature: string) => void; } class MyButton extends React.Component<MyButtonProps, {}> { handlePress = () => { this.props.onPress(this.props.signature); }; render() { const { onPress, ...restProps } = this.props; return <Button {...restProps} onPress={this.handlePress} />; } } const App = () => { const _onPressButton = (signature: string) => { Alert.alert(signature); // fetch(`http://12.18.1.11/switch?${signature}`); }; return ( <View style={styles.container}> <View style={styles.buttonContainer}> <MyButton signature="binary=000011110000011&protocol=1&pulselength=133" onPress={_onPressButton} title="LED1 (ON)" /> </View> <View style={styles.buttonContainer}> <MyButton signature="binary=000111110&protocol=1&pulselength=133" onPress={_onPressButton} title="LED1 (OFF)" /> </View> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', }, buttonContainer: { margin: 20, }, }); export default App;
方案2:直接在父组件绑定参数(无需自定义组件)
如果不需要复用 MyButton,可以直接给每个按钮的 onPress 用箭头函数绑定参数:
const App = () => { const _onPressButton = (signature: string) => { Alert.alert(signature); // fetch(`http://12.18.1.11/switch?${signature}`); }; return ( <View style={styles.container}> <View style={styles.buttonContainer}> <Button onPress={() => _onPressButton("binary=000011110000011&protocol=1&pulselength=133")} title="LED1 (ON)" /> </View> <View style={styles.buttonContainer}> <Button onPress={() => _onPressButton("binary=000111110&protocol=1&pulselength=133")} title="LED1 (OFF)" /> </View> </View> ); };
方案3:用函数组件重写MyButton(符合RN当前最佳实践)
现在RN推荐使用函数组件,改写后的 MyButton 更简洁:
import React from 'react'; import { Button, ButtonProps } from 'react-native'; interface MyButtonProps extends ButtonProps { signature: string; onPress: (signature: string) => void; } const MyButton = ({ onPress, signature, ...rest }: MyButtonProps) => { const handlePress = () => onPress(signature); return <Button {...rest} onPress={handlePress} />; };
补充说明
不要把Web端React的事件机制直接套用到React Native上,RN的原生组件事件回调大多不会传递包含组件props的事件对象,想要获取组件的自定义属性,最好通过回调参数传递的方式实现。
内容的提问来源于stack exchange,提问作者Papp Zoltán
相关产品推荐
相关产品推荐

