javascript - 将输入中的值添加到数组中在 React 中不起作用

标签 javascript reactjs

我是 React 新手,想要将输入中的值添加到数组中,但当我尝试实现这一目标时什么也没有发生。如果有什么不清楚的地方,请告诉我。这是我正在使用的代码:

class Engine extends React.Component {
  render() {
    let types = ["Diesel", "Gazoline", "Simple"];
    return (
      <div>
        <Car type={types} />
      </div>
    );
  }
}

class Car extends React.Component {
  openm(e) {
    let addItem = e.target.elements.type.value;

    if (addItem) {
      this.props.type.push(additem);
    }
  }

  render() {
    return (
      <div>
        <h1>
          {this.props.type.map((item, index) => {
            return <p key={index}>{item}</p>;
          })}
        </h1>
        <form onSubmit={this.openm}>
          <input type="text" name="type" />
          <button>Remo all</button>
        </form>
      </div>
    );
  }
}

const box = document.querySelector(".mir");

ReactDOM.render(<Engine />, box);

如果您查看 Car 类的 openm 方法中的代码,我正在尝试通过 props 访问数组。

最佳答案

您的代码有一些问题,我会尽力尽可能彻底地解释它们。

1) Prop 是不可变的。这意味着您无法通过执行诸如 this.props.types.push(blah) 之类的操作来更改它们。这不会对您的应用程序造成任何视觉变化或重新渲染。看起来就像什么都没发生一样。

解决方案:改用React-state,简单来说可以理解为每个组件拥有的跟踪机制,用于跟踪组件的状态和数据。不要在渲染中定义类型数组,而是在状态中定义一个类型数组。然后我们可以自由地添加到该数组中。每当更新组件的状态时,组件就会重新呈现以反射(reflect)这些更改(如果需要)。

2) this 关键字的重要性。组件方法需要绑定(bind)到组件的执行上下文,以便 this 关键字按预期工作。进一步阅读:Check in React JS if a checkbox is active or not

解决方案:将 open 定义为箭头函数,以便将 this 关键字隐式绑定(bind)到组件。因此,您可以访问 this.setState()this.props.

3) 表单提交后会自然刷新页面。在这种情况下您不希望出现这种情况。

解决方案:使用event.preventDefault()

工作沙箱:https://codesandbox.io/s/nice-pine-c0ied

完整代码:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class Engine extends React.Component {
  state = {
    types: ["Diesel", "Gazoline", "Simple"]
  };

  addItem = item => {
    this.setState({
      types: [...this.state.types, item]
    });
  };

  render() {
    return (
      <div>
        <Car type={this.state.types} addItem={this.addItem} />
      </div>
    );
  }
}

class Car extends React.Component {
  open = e => {
    e.preventDefault();

    let addItem = e.target.elements.type.value;

    if (addItem) {
      this.props.addItem(addItem);
    }
  };

  render() {
    return (
      <div>
        <h1>
          {this.props.type.map((item, index) => {
            return <p key={index}>{item}</p>;
          })}
        </h1>
        <form onSubmit={this.open}>
          <input type="text" name="type" />
          <button>Remo all</button>
        </form>
      </div>
    );
  }
}

const box = document.querySelector(".mir");

const rootElement = document.getElementById("root");
ReactDOM.render(<Engine />, rootElement);

关于javascript - 将输入中的值添加到数组中在 React 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57551258/

相关文章:

javascript - 错误 : FS. 集合无法删除属于: "images"的文件,而不是: "cfs.images.filerecord"

javascript - 在 React 和 Meteor 中使用 Coral Talk

javascript - 有没有办法通过 props 将 FontAwesomeIcon 组件传递给 ReactHTMLTableToExcel 组件?

javascript - react Hook 中的事件监听器 onMouseMove : event object is undefined or clientX/Y are null

javascript - ( react )用参数去抖动

javascript - 具有多个根和动态需求的 Webpack

javascript - 使用 PHP 数组中的 JSON.parse 时出现“意外标记”

javascript - 如何在 d3.js 中的 svg 中拖放一组矩形?

reactjs - 检查 React 中嵌套路由的 router.isActive

javascript - 从 UL jquery 中删除一个(没有 id)元素