React无限循环中的可重用组件

时间:2019-04-18 18:49:37

标签: reactjs infinite-loop

我正在尝试创建一个虚拟项目,以“反应”添加一名员工。 我使用了带有bulma css的表单和一个输入组件作为该表单的可重用组件。当我运行npm start时,它已成功编译,但是页面无法加载,并且我的代码中似乎存在一个无限循环。有人可以看一下代码,让我知道我在做什么错吗?

import React, { Component } from 'react'
import Input from './input'

class EmployeeGeneral extends Component {
 state = {
   Employee: { FirstName: '', LastName: '', MeliCode: '' }
 }

 handleSubmit = e => {
   e.preventDefault()
 }

 handleChange = ({ currentTarget: input }) => {
   const Employee = { ...this.state.Employee }
   Employee[input.name] = input.value
   this.setState({ Employee })
 }
 render() {
   const { Employee } = this.state

   return (
     <main className="container">
       <h1 className="title">Employee General</h1>
       <form onSubmit={this.handleSubmit}>
         <div className="columns">
           <div className="column">
             <Input
               name="firstName"
               label="First Name"
               value={Employee.FirstName}
               onChange={this.handleChange}
             />

             <div className="control">
               <button className="button is-primary">Add Employee</button>
             </div>
           </div>
           <div className="column">
             <Input
               name="lastName"
               label="Last Name"
               value={Employee.LastName}
               onChange={this.handleChange}
             />
           </div>
           <div className="column">
             <Input
               name="meliCode "
               label="Meli Code"
               value={Employee.MeliCode}
               onChange={this.handleChange}
             />
           </div>
         </div>
       </form>
     </main>
   )
 }
}

export default EmployeeGeneral

import React from 'react'

const Input = ({ name, label, onChange, value }) => {
  return (
    <div className="field">
      <label htmlFor={name} className="label">
        {label}
      </label>
      <div className="control">
        <Input
          value={value}
          onChange={onChange}
          autoFocus
          id={name}
          type="text"
          className="input"
          placeholder={label}
          name={name}
        />
      </div>
      <p className="help">{label}</p>
    </div>
  )
}

export default Input

1 个答案:

答案 0 :(得分:2)

您正在递归使用Input组件。将内部Input更改为常规input

const Input = ({ name, label, onChange, value }) => {
  return (
    <div className="field">
      <label htmlFor={name} className="label">
        {label}
      </label>
      <div className="control">
        <input
          value={value}
          onChange={onChange}
          autoFocus
          id={name}
          type="text"
          className="input"
          placeholder={label}
          name={name}
        />
      </div>
      <p className="help">{label}</p>
    </div>
  )
}