Javascript 如何将项目添加到列表中

Javascript 如何将项目添加到列表中,javascript,reactjs,list,react-native,variables,Javascript,Reactjs,List,React Native,Variables,主页 export class Diet extends Component { constructor(props) { super(props); this.state = { list: [], }; } addToList(item) { const list = [...this.state.list, item]; this.set

主页

    export class Diet extends Component {
      constructor(props) {
        super(props);
        this.state = {
          list: [],
        };
      }
    
      addToList(item) {
        const list = [...this.state.list, item];
        this.setState({ list });
      }
    
      render() {
        return (
          <View>
            <Text style={styles.txtYourMeals}>Your Meals</Text>
                     <FoodList items={this.state.list} />  <--------
          </View>
        );
      }
    }
    
 export default Diet;
导出类饮食扩展组件{
建造师(道具){
超级(道具);
此.state={
名单:[],
};
}
地址列表(项目){
const list=[…this.state.list,item];
this.setState({list});
}
render(){
返回(
你的饭菜
添加食物
);
}

因此,我试图让用户在
FoodCreate
页面的文本输入中键入
食品名称
,然后按下按钮
复选标记
,将该食品名称添加到
食品列表
,该列表显示在
主页
中。我开始了,但不知道如何继续。这是wh的基本杂货购物清单我可以键入食物名称并将其添加到列表中,每次都插入一个新项目。

您需要的是告诉父组件,即
主页
,已经创建了一个新的食物项目

在您的
主页中应该是这样的

render() {
        return (
          <>
            <FoodCreate addToList={addToList}/>
            <View>
              <Text style={styles.txtYourMeals}>Your Meals</Text>
                     <FoodList items={this.state.list} />  <--------
            </View>
        );
      }
render(){
返回(
你的饭菜

不要使用
(FoodName)=>setFoodName(FoodName)
尝试
(e)=>setFoodName(e.target.value)
是的,但到目前为止,该应用程序不符合我的要求,我正在尝试了解如何使其工作。您正在尝试将食物名称添加到一个数组中,以在另一个组件中显示,对吗?您需要将要操作的数组向下传递到子组件,以便它们修改和显示数据。因此,在您的情况下,您想在列表数组中
.push()
您的食物名称。
export default function FoodCreate({ navigation: { goBack } }) {
  const [FoodName, setFoodName] = useState("");

  return (
    <Container>
      <Header>
        <Left>
          <Button transparent>
            <Icon
              name="arrow-back"
              onPress={() => goBack()}
              style={{ fontSize: 25, color: "red" }}
            />
          </Button>
        </Left>
        <Body>
          <Title>Add Food</Title>
        </Body>
        <Right>
          <Button transparent>
            <Icon  <-----------
              name="checkmark"
              style={{ fontSize: 25, color: "red" }}/>
          </Button>
        </Right>
      </Header>
        <TextInput
          placeholder="Food Name"
          placeholderTextColor="white"
          style={styles.inptFood}
          value={FoodName}
          onChangeText={(FoodName) => setFoodName(FoodName)}
        />
    </Container>
  );
}
render() {
        return (
          <>
            <FoodCreate addToList={addToList}/>
            <View>
              <Text style={styles.txtYourMeals}>Your Meals</Text>
                     <FoodList items={this.state.list} />  <--------
            </View>
        );
      }