【问题标题】:ReactJS Form: Parent Component state updates, but Child's field gets emptied & props remain unchangedReactJS 表单:父组件状态更新,但子字段被清空且道具保持不变
【发布时间】:2020-08-23 14:25:15
【问题描述】:

我已经为动态表单编写了 ReactJS 代码来收集学生详细信息。可以添加或删除任意数量的学生。父组件是App,子组件是StudentsFormElement,它呈现一个学生输入字段。添加和删​​除字段工作得很好。


问题:我无法在表单字段中输入超过一个字符,并且在输入后它们会立即清除。使用 DevTools,我可以看到输入的字符反映在父组件的状态中,但更改无法通过道具向下传播到子组件。因此,DOM 清除为原始状态。 (注意:我发现了几个相似的问题,但没有一个回答这个特定的问题)。 忽略 onStudentsChange() 中被注释掉的 else 条件。它处理添加和删除学生。


代码沙盒: https://codesandbox.io/embed/inspiring-kare-qb9hz

应用(父级):

class App extends React.Component {
  constructor(props) {
    super(props)
    let studentsFormElementsTemp = []
    let tempSTUDENTS = {0: ["", ""]}
    this.state = {
      STUDENTS: tempSTUDENTS
    }
    studentsFormElementsTemp.push(<StudentsFormElement id="0" student={this.state.STUDENTS[0]} onStudentsChange={this.onStudentsChange} />)
    this.state = {
      studentsFormElements: studentsFormElementsTemp,
      studentsElementsIdArray: [0],
      STUDENTS: tempSTUDENTS
    } 
  }

  onStudentsChange = (e) => {
    if (e.target.name === "studentId" || e.target.name === "studentName") {
      let tempSTUDENTS = this.state.STUDENTS
      if (e.target.name === "studentId") {
        tempSTUDENTS[e.target.id][0] = e.target.value
      }
      else {
        tempSTUDENTS[e.target.id][1] = e.target.value
      }
      this.setState({
        STUDENTS: tempSTUDENTS
      })
    } else { //IGNORE. DEALS WITH 'X' and '+' BUTTONS.
      /*let studentsFormElementsTemp = this.state.studentsFormElements
      let studentsElementsIdArrayTemp = this.state.studentsElementsIdArray
      let tempSTUDENTS = this.state.STUDENTS
      if (e.target.id === "+") {
        tempSTUDENTS[studentsElementsIdArrayTemp[studentsElementsIdArrayTemp.length - 1] + 1] = ["", ""]
        this.setState({
          STUDENTS: tempSTUDENTS
        })
        studentsFormElementsTemp.push(<StudentsFormElement id={studentsElementsIdArrayTemp[studentsElementsIdArrayTemp.length - 1] + 1} student={this.state.STUDENTS[studentsElementsIdArrayTemp[studentsElementsIdArrayTemp.length - 1] + 1]} onStudentsChange={this.onStudentsChange} />)
        studentsElementsIdArrayTemp.push(studentsElementsIdArrayTemp[studentsElementsIdArrayTemp.length - 1] + 1)
        this.setState({
            studentsFormElements: studentsFormElementsTemp,
            studentsElementsIdArray: studentsElementsIdArrayTemp
        })
      } else {
        let studentIndex = studentsElementsIdArrayTemp.indexOf(parseInt(e.target.id))
        studentsFormElementsTemp.splice(studentIndex, 1)
        studentsElementsIdArrayTemp.splice(studentIndex, 1)
        delete tempSTUDENTS[e.target.id]
        this.setState({
            studentsFormElements: studentsFormElementsTemp,
            studentsElementsIdArray: studentsElementsIdArrayTemp,
            STUDENTS: tempSTUDENTS
        })
      }
    */}
  }

  render() {
    return (
        <div>
            <h2 style={{textAlign: "center", display: "inline-block"}}>Students</h2><Button id="+" style={{display: "inline-block"}} variant="success" onClick={this.onStudentsChange}>+</Button>
            <form>
                {this.state.studentsFormElements}
            </form>
        </div>
    )
  }
}

StudentsFormElement(子):

class StudentsFormElement extends React.Component {
  render() {
    return (
      <InputGroup className="mb-3">
        <FormControl name="studentId" id={this.props.id} value={this.props.student[0]} placeholder="Id" onChange={this.props.onStudentsChange} />
        <FormControl name="studentName" id={this.props.id} value={this.props.student[1]} placeholder="Name" onChange={this.props.onStudentsChange} />
        <InputGroup.Append style={{display: "inline-block"}}>
          <Button id={this.props.id} variant="danger" onClick={this.props.onStudentsChange}>X</Button>
        </InputGroup.Append>
      </InputGroup>
    )
  }
}

这是一个只有一个学生字段且没有添加/删除按钮的版本。由于我直接在父组件的 render() 中使用了子组件,因此可以输入。但我需要让它与上述代码等多个学生领域一起工作。 https://codesandbox.io/s/quirky-colden-gkiz6

【问题讨论】:

    标签: javascript reactjs forms react-bootstrap


    【解决方案1】:

    起初,FormControl 字段中的值可能未定义,因为 this.props.student[0] 未定义 删除 FormControl 中的 value 属性 并在 defaultValue 属性中分配 props 值

    <FormControl name="studentId" id={this.props.id} defaultValue={this.props.student[0]} placeholder="Id" onChange={this.props.onStudentsChange} />
    <FormControl name="studentName" id={this.props.id} defaultValue={this.props.student[1]} placeholder="Name" onChange={this.props.onStudentsChange} />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 2021-06-08
      • 2015-12-02
      • 2018-10-29
      • 2018-10-05
      • 2020-09-17
      • 1970-01-01
      相关资源
      最近更新 更多