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

问题描述 投票:1回答:1

我正在尝试制作一个“添加员工”的虚拟项目。我使用了一个带有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

reactjs infinite-loop
1个回答
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>
  )
}
© www.soinside.com 2019 - 2024. All rights reserved.