【发布时间】:2021-07-06 20:15:32
【问题描述】:
饮食.js
export class Diet extends Component {
constructor(props) {
super(props);
this.state = {
list: [],
};
this.addToList = this.addToList.bind(this);
}
addToList(item) {
const list = [...this.state.list, item];
this.setState({ list });
}
render() {
<FoodCreate addToList={this.addToList} />
return (
<FoodList items={this.state.list} />
)}
食物创造
export class FoodCreate extends Component {
constructor(props) {
super(props);
this.state = {
FoodName: "",
calories: 0,
};
}
render() {
return (
<Button transparent>
<Icon
name="checkmark"
style={{ fontSize: 25, color: "red" }}
onPress={() => this.props.addToList(FoodName, calories)}
/>
</Button>
<TextInput
placeholder="Food Name"
placeholderTextColor="white"
style={styles.inptFood}
value={FoodName}
onChangeText={(FoodName) => this.setState({ FoodName: FoodName })}
/>
<TextInput
placeholder="Calories"
placeholderTextColor="white"
style={styles.inptMacros}
keyboardType="numeric"
value={calories}
maxLength={5}
onChangeText={(calories) => this.setState({ calories: calories })}
/>
食物清单
export class FoodList extends Component {
render() {
return (
<Content>
<List>
<ListItem itemDivider>
<Text>Food</Text>
{this.props.items.map((item, index) => {
return (
<ListItem key={index}>
<Text>{item.FoodName}</Text>
<Text>{item.calories}</Text>
</ListItem>
);
})}
</ListItem>
</List>
</Content>
);
}
}
export default FoodList;
嗨,我是编程和 React Native 的新手,所以我试图通过让用户键入 FoodName 和 Calories 并按下图标来创建一个杂货清单:签入 FoodCreate 页面,然后在FoodList 页面中列出它,在我运行代码的那一刻给我一个错误:_this2.props.addToList is not a function,我尝试了很多解决方案,但我不确定错误在哪里。
【问题讨论】:
-
您的代码无效,令人困惑(
addToList采用 1 个参数还是 2 个参数?),而且您还没有创建可以重现您的问题的示例。
标签: javascript reactjs list react-native variables