我在本机博览会应用程序中有一个ItemForm
组件,我想同时使用它进行创建和更新。它是一个功能组件,我正在尝试从父组件传递处理程序以创建新项目或更新现有项目。我很难理解如何将onPress
处理程序从父类组件传递到功能性子窗体Component。
父项:
import React, { Component } from "react";
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import ItemForm from './components/ItemForm';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default class App extends Component {
handleSubmit = ({ name }) => {
alert(name);
// todo: get form data and create or update database
}
render() {
return (
<View style={styles.container}>
<Card>
<ItemForm onSubmit={() => this.handleSubmit}/>
</Card>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
});
ItemForm.js
import React, { useState } from "react";
import { View, Text, StyleSheet } from "react-native";
import { Button, Card, Icon, Input } from "react-native-elements";
export default function ItemForm({ onSubmit }) {
const [name, setName] = useState("");
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>Add an Item</Text>
</View>
<Card
containerStyle={{
height: "80%",
margin: 0,
elevation: 1,
borderWidth: 0,
shadowOpacity: 0,
shadowRadius: 0,
}}
>
<Input
label="Item Name"
labelStyle={styles.itemText}
placeholder="Name Here"
onChangeText={(name) => setName(name)}
/>
<Button
icon={
<Icon
name="check-circle"
size={20}
style={{ paddingRight: 10 }}
onPress={onSubmit({name: name})}
/>
}
title="Save Item"
/>
</Card>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "column",
},
header: {
alignItems: "center",
paddingTop: 40,
},
headerText: {
fontSize: 32,
},
itemText: {
fontSize: 25,
}
});
当前正在抛出:
onSubmit is not a function. (In 'onSubmit({name: name})', 'onSubmit' is undefined)
我已经通过阅读文档here尝试了各种不同的传递或调用函数的语法,但是遇到了许多类似Please attach a method to this component
的错误,我似乎无法克服?
答案 0 :(得分:0)
onPress
应该是调用onSubmit
的函数,而不是调用onSubmit
(onPress={onSubmit({name: name})}
)的返回值。onPress
必须位于按钮上。this.handleSubmit
,而不是传回this.handleSubmit
(onSubmit={() => this.handleSubmit}
)的函数:因此在App中:
<ItemForm onSubmit={this.handleSubmit}/>
在ItemForm中:
<Button
onPress={() => onSubmit({name: name})}
icon={
<Icon
name="check-circle"
size={20}
style={{ paddingRight: 10 }}
/>
}
title="Save Item"
/>