javascript - 使用传播运算符 react 添加项目

标签 javascript reactjs object add

我的问题是关于 React 添加和编辑项目。我想在数组中添加对象(包含数组中的数量、数量单位、名称的对象)console.log 没问题,但没有添加对象。在我的表单上无法显示此功能的结果。我想从 API 添加新的成分列表对象。我不知道我的 Prop 或状态是否不好

import React, { Component } from "react";
import {
  FormGroup,
  FormControl,
  ControlLabel,
  InputGroup
} from "react-bootstrap";
export default class AddIngredient extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ingredients: [],
      amount: " ",
      amountUnit: " ",
      name: " "
    };
  }

  onChangeAmount = e => {
    this.setState({ amount: e.target.value });
    console.log("amount was changed");
  };

  onChangeAmountUnit = e => {
    this.setState({ amountUnit: e.target.value });
    console.log("amount unit was changed");
  };
  onChangeName = e => {
    this.setState({ name: e.target.value });
    console.log("name was changed");
  };

  onClickAddIngredient = e => {
    const { amount, amountUnit, name } = this.state;
    const newIngredient = { amount, amountUnit, name };
    this.setState({ ingredients: [...this.state.ingredients, newIngredient] });

    console.log("was added");
  };

  render() {
    const { amount, amountUnit, name } = this.props;
    return (
      <React.Fragment>
        <FormGroup>
          <ControlLabel>Přidat ingredienci</ControlLabel>
          <InputGroup className="frow">
            <FormControl
              type="number"
              placeholder="Množství"
              min="0"
              value={amount}
              onChange={this.onChangeAmount}
            />
            <FormControl
              type="text"
              placeholder="Jednotka"
              value={amountUnit}
              onChange={this.onChangeAmountUnit}
            />
          </InputGroup>
          <InputGroup>
            <FormControl
              type="text"
              placeholder="Název"
              value={name}
              onChange={this.onChangeName}
            />
            <InputGroup.Addon>
              <button onClick={this.onClickAddIngredient} className={"addon"}>
                Přidat
              </button>
            </InputGroup.Addon>
          </InputGroup>
        </FormGroup>
      </React.Fragment>
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

import React, { Component } from "react";

import IngredientItems from "./IngredientItems";
import AddIngredient from "./AddIngredient";
import Directions from "./Directions";
import { FormGroup, Button, ButtonGroup, Grid } from "react-bootstrap";
import BasicInfo from "./BasicInfo";
export default class RecipeForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: props.title || "",
      servingCount: props.servingCount,
      preparationTime: props.preparationTime,
      sideDish: props.sideDish,
      directions: props.directions,
      ingredients: props.ingredients
    };
  }

  onChange = (key, value) => {
    this.setState({ [key]: value });
  };

  render() {
    const { onCancel } = this.props;
    const {
      ingredients,
      title,
      servingCount,
      sideDish,
      preparationTime,
      directions
    } = this.state;

    return (
      <Grid>
        <ButtonGroup
          className="pull-right"
          size="lg"
          aria-label="Basic example"
        >
          <Button onClick={this.onSave} bsStyle="success">
            Uložit
          </Button>
          <Button onClick={onCancel} bsStyle="default">
            Zrušit
          </Button>
        </ButtonGroup>
        <BasicInfo
          title={title}
          preparationTime={preparationTime}
          servingCount={servingCount}
          sideDish={sideDish}
          onChange={this.onChange}
        />
        <IngredientItems ingredients={ingredients} />
        <Directions directions={directions} onChange={this.onChange} />
        <AddIngredient onChange={this.onChange} />
        <FormGroup />
      </Grid>
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

最佳答案

您的 AddIngredient 组件中有本地状态 ingredients,但它从未真正呈现。

看起来您想要做的是将一个处理程序传递给该组件,它会更新父组件中的 ingredient 数组。

AddIngredient.js

onClickAddIngredient = e => {
  const { amount, amountUnit, name } = this.state;
  const newIngredient = { amount, amountUnit, name };

  // call handler from parent and update there
  this.props.onAdd(newIngredient);

  console.log("was added");
};

RecipeForm.js

onAddIngredient = (newIngredient) => {
  this.setState({ ingredients: [...this.state.ingredients, newIngredient] });
};

此外,您似乎不需要将 onChange 传递给该组件,因为输入字段只是保持在其本地状态。所以你可以像这样渲染它并添加新的处理程序:

<AddIngredient onAdd={this.onAddIngredient} />

然后您可以删除子组件中的本地状态 ingredients,因为它未被使用。

关于javascript - 使用传播运算符 react 添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54582110/

相关文章:

javascript - 如果我页面上的 Div Id 不起作用,则函数重定向

reactjs - 将 expandIcon 图标向右移动并从扩展表中移除空白区域 Ant Design reatc js

javascript - 当没有 child 时删除图标

java - 执行这段代码时创建了多少个对象? - java

php - 获取所有多个列表框值

javascript - 有什么办法可以写这个更短/更干燥的东西吗?

javascript - 集成人力车 JS 和 React JS

javascript - 如何在 javascript/jQuery 中获取父对象属性

java - 添加两个对象——难以理解接受一个对象作为参数

javascript - Socket.io ReferenceError 客户端未定义