我是 React Native(和 React)的新手,我正在尝试将函数作为 prop 传递给组件。
我的目标是创建一个组件,它的 onPress 功能可以由组件的实例化器设置,以便更可重用。
到目前为止,这是我的代码。
应用程序.js
import React, { Component } from 'react';
import { View } from 'react-native';
import TouchableButton from './components/touchable-button';
export default class App extends Component<Props> {
constructor () {
super();
}
handlePress () {
// this should be called when my custom component is clicked
}
render () {
return (
<View>
<TouchableButton handlePress={this.handlePress.bind(this)}/>
</View>
);
}
}
TouchableButton.js
import React, { Component } from 'react';
import { TouchableHighlight } from 'react-native';
import AppButton from "./app-button";
export default class TouchableButton extends Component {
handlePress;
constructor(props){
super(props);
}
render () {
return (
<TouchableHighlight onPress={
this.props.handlePress
}>
<AppButton/>
</TouchableHighlight>
);
}
}
我将 handlePress 函数作为props handlePress 传递。我希望 TouchableButton 的props包含该功能,但它不存在。