简体   繁体   English

React 尝试编辑输入但出现错误

[英]React Trying to edit input but got an error

I'm working on the edit/update the prices in the price list in my React app.我正在编辑/更新我的 React 应用程序中价目表中的价格。 I'm almost close but was unable to input any changes.我几乎接近但无法输入任何更改。 Every time I tried to change the price in the input, I get an error saying "TypeError: onChange is not a function"...每次我尝试更改输入中的价格时,都会收到一条错误消息“TypeError: onChange is not a function”...

I'm trying to write my code that's almost similar to this tutorial: https://medium.com/the-andela-way/handling-user-input-in-react-crud-1396e51a70bf#8858我正在尝试编写与本教程几乎相似的代码: https://medium.com/the-andela-way/handling-user-input-in-react-crud-1396e51a70bf#8858

So far, I was able to toggle the price between input field and back but I'm trying to edit the input to save any changes...What am I missing?到目前为止,我能够在输入字段之间切换价格并返回,但我正在尝试编辑输入以保存任何更改......我错过了什么? I kept checking between my code and this tutorial to make sure everything is working...我一直在检查我的代码和本教程,以确保一切正常......

Here's my code (functions) in the Parent component, PriceForm.js :这是我在 Parent 组件PriceForm.js中的代码(函数):

toggleItemEditing = index => {
    this.setState({
      priceArr: this.state.priceArr.map((item, itemIndex) => {
        if (itemIndex === index) {
          return {
            ...item,
            isEditing: !item.isEditing
          }
        }
        return item;
      })
    });
  };

  handlePriceUpdate = (event, index) => {
    const target = event.target;
    const value = target.value;
    const number = target.number;
    this.setState({
      priceArr: this.state.priceArr.map((item, itemIndex) => {
        if (itemIndex === index) {
          return {
            ...item,
            [number]: value
          }
        }
        return item;
      })
    });
    console.log("price update", event);
  };

and where it's called in:以及它的调用位置:

{this.state.priceArr.map((props, index) => (
              <PriceBox
                {...props}
                key={props.date}
                toggleEditing={this.toggleItemEditing}
                handleDeletePrice={this.handleDeletePrice}
                onChange={this.handlePriceUpdate}
              />
            ))}

And here's my code for the Child component, SinglePriceBox.js :这是我的子组件SinglePriceBox.js的代码:

import React, { Component } from "react";

export default class SinglePricebox extends Component {
  constructor(props) {
    super(props);

    this.state = {
    isInEditMode: false,
    todaydate: this.props.date
  };

  this.toggleEditPriceSubmission = this.toggleEditPriceSubmission.bind(this);
}

toggleEditPriceSubmission() {
  this.setState(state => ({ isInEditMode: !state.isInEditMode }));
}


  render() {
    const { isInEditMode, onChange, index } = this.state;
    return (
      <div className="pricebox">
        <article className="pricetable">
          <table>
            <tbody>
              <tr>
                <td className="date-width">{this.props.date}</td>
                <td className="price-width">
                {isInEditMode ? (
                    <input type="text" name="number" value={this.props.number} onChange={event => onChange(event, index)} />
                  ) : (
                    this.props.number
                  )}
                </td>
                <td className="editing-btn">
                  <button
                    type="button"
                    className="edit-btn"
                    onClick={this.toggleEditPriceSubmission}
                  >
                    {isInEditMode ? "Save" : "Edit"}
                  </button>
                </td>
                <td>
                {this.props.handleDeletePrice && (
                  <button
                    type="button"
                    className="delete-btn"
                    onClick={() => this.props.handleDeletePrice(this.props.date)}
                    >
                      X
                    </button>
                    )}
                </td>
              </tr>
            </tbody>
          </table>
        </article>
      </div>
    );
  }
}

You can check out my demo at https://codesandbox.io/s/github/kikidesignnet/caissa .您可以在https://codesandbox.io/s/github/kikidesignnet/caissa查看我的演示。 You will be able to check out the error if you click on Prices button, then click on Edit button to change the price in the input field that appears.如果您单击Prices按钮,您将能够检查错误,然后单击Edit按钮以更改出现的输入字段中的价格。

In the following line:在以下行中:

<input type="text" name="number" value={this.props.number} onChange={event => onChange(event, index)} />

You're calling this.state.onChange but there is no onChange in your state:您正在调用 this.state.onChange 但您的 state 中没有 onChange:

this.state = {
    isInEditMode: false,
    todaydate: this.props.date
  };

After looking at your codesandbox, it seems that onChange is passed as a props to PriceBox, so you should do this in SinglePriceBox render():查看您的代码和框后,似乎 onChange 作为道具传递给 PriceBox,因此您应该在 SinglePriceBox render() 中执行此操作:

const { isInEditMode, index } = this.state;
const { onChange } = this.props;

This will remove the error you were having, but the update still doesn't work because target.number is undefined in PriceForm.handlePriceUpdate:(这将消除您遇到的错误,但更新仍然不起作用,因为 target.number 在 PriceForm.handlePriceUpdate 中未定义:(

However target.name is defined and equal to 'number' which is a valid key in your price list但是 target.name 已定义并等于“数字”,这是您的价目表中的有效键

import React, { Component } from "react";

export default class SinglePricebox extends Component {
  constructor(props) {
    super(props);

    this.state = {
    isInEditMode: false,
    todaydate: this.props.date
  };

  this.toggleEditPriceSubmission = this.toggleEditPriceSubmission.bind(this);
this.handleChange = this.handleChange.bind(this);
}

toggleEditPriceSubmission() {
  this.setState(state => ({ isInEditMode: !state.isInEditMode }));
}

handleChange = (e, index) => {
  // write your code here
}


  render() {
    const { isInEditMode, index } = this.state;
    return (
      <div className="pricebox">
        <article className="pricetable">
          <table>
            <tbody>
              <tr>
                <td className="date-width">{this.props.date}</td>
                <td className="price-width">
                {isInEditMode ? (
                    <input type="text" name="number" value={this.props.number} onChange={event => this.handleChange(event, index)} />
                  ) : (
                    this.props.number
                  )}
                </td>
                <td className="editing-btn">
                  <button
                    type="button"
                    className="edit-btn"
                    onClick={this.toggleEditPriceSubmission}
                  >
                    {isInEditMode ? "Save" : "Edit"}
                  </button>
                </td>
                <td>
                {this.props.handleDeletePrice && (
                  <button
                    type="button"
                    className="delete-btn"
                    onClick={() => this.props.handleDeletePrice(this.props.date)}
                    >
                      X
                    </button>
                    )}
                </td>
              </tr>
            </tbody>
          </table>
        </article>
      </div>
    );
  }
}

the problem is in how you pass your function as a prop.问题在于您如何将 function 作为道具传递。 You should pass the function call in this way:您应该以这种方式传递 function 调用:

<PriceBox
   {...props}
   [...]
   onChange={(e) => this.handlePriceUpdate(e, index)}
/>

Then call it in your child component:然后在您的子组件中调用它:

<input 
  type="text" 
  [...]
  onChange={event => this.props.onChange(event, index)} 
/>

Also, I would not using index here, I would rather use an ID from your object instead另外,我不会在这里使用索引,我宁愿使用 object 中的 ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试在 create-react-app 中导入 npm 时出错 - Error while trying to import npm got in create-react-app 编辑文本输入反应 - edit text input React 尝试使用react编辑数据 - Trying to edit data using react 我已经输入了一个独特的“关键”道具,但仍然有错误要求我在 React 中输入它 - I have input a unique "key" prop but still got error asking me to input it in React 反应形式输入在编辑时不改变 - React form input not changing on edit 尝试在 JS/JQury 中单击 2 次或更多次来获取“已检查输入”的值时出错 - Got error when trying to get value of a "checked input" using 2 or more times clicking on it in JS/JQury 我尝试在 iOS 和 Android 设备上运行我的 React 应用程序时遇到此错误 - I got this error trying to run my React app on a iOS and Android device 反应得到未知道具的错误 - react got error of unknown props React JS 错误 - 期望“CALC”、...........“维度”、“数字”,输入意外结束 CompileError: Begins at CSS selector undefined - React JS error - Expecting "CALC", ,..........."dimension", "number", got unexpected end of input CompileError: Begins at CSS selector undefined 尝试编辑“ React Native init”文件结构 - Trying to edit “React Native init” file structure
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM