📜  如何使用单个函数以反应形式处理多个输入字段?

📅  最后修改于: 2022-05-13 01:56:47.822000             🧑  作者: Mango

如何使用单个函数以反应形式处理多个输入字段?

形式有两种,一种是非受控形式,另一种是受控形式。在存储在 DOM 中的输入字段的不受控制的表单值中,当我们想要使用这些值时,我们必须到达 DOM 并提取每个输入字段的值。现在在控制中,我们不允许将值存储在 DOM 中,但值作为反应组件的状态存储并随着用户交互动态更新。为此,我们使用事件处理程序onChange并执行更新状态值的回调。现在对于单个输入字段,我们使用一个 handleChange 回调,但如果输入字段是多个,那么我们必须创建多个 handleChange 回调来更新每个输入字段的状态。幸运的是,情况并非如此。 JavaScript 为我们提供了 ES2015 现代语法,以简单的方式执行这种复杂的工作。

ES2015 引入了基于称为计算属性名称的 JavaScript 表达式使用动态键创建对象的能力。我们使用计算属性名称来根据输入的名称属性更新所有输入字段的状态。

句法 :

const obj = {
   : value
}

示例 1:此示例显示如何使用单个 handleChange函数处理多个表单输入字段。

  • index.js:

    Javascript
    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'
      
    ReactDOM.render(, document.querySelector('#root'))


    Javascript
    import React from 'react'
    import Form from './Form'
      
    //Functional component
    const App = () => {
      //render single App component
      return(
        
      ) }    export default App


    Javascript
    import React,{ Component } from 'react'
      
    class Form extends Component{
      constructor(props){
        super(props)
        this.state = { email:'',name:'', age:null, address:'',phoneNo:''}
        this.handleChange = this.handleChange.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this)
      }
      
      // Form submitting logic, prevent default page refresh 
      handleSubmit(event){
        const { email, name, age, address, phoneNo } = this.state
        event.preventDefault()
        alert(`
          ____Your Details____\n
          Email : ${email}
          Name : ${name}
          Age : ${age}
          Address : ${address}
          Phone No : ${phoneNo}
        `)
      }
      
      // Method causes to store all the values of the 
      // input field in react state single method handle 
      // input changes of all the input field using ES6 
      // javascript feature computed property names
      handleChange(event){
        this.setState({
          // Computed property names
          // keys of the objects are computed dynamically
          [event.target.name] : event.target.value
        })
      }
      
      // Return a controlled form i.e. values of the 
      // input field not stored in DOM values are exist 
      // in react component itself as state
      render(){
        return(
          
            
                                  
            
                                  
            
                                  
            
                                  
            
                                  
            
                       
               )   } }    export default Form


    Javascript
    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'
      
    ReactDOM.render(, document.querySelector('#root'))


    Javascript
    import React from 'react';
    import BoxList from './BoxList'
      
    const App = () => {
      //App renders single BoxList component
      return(
        
      )
    }
      
    export default App


    Javascript
    import React, { Component } from 'react'
    import { v4 as uuid } from 'uuid'
    import NewBoxForm from './NewBoxForm'
    import Box from './Box'
      
    class BoxList extends Component{
      constructor(props){
        super(props)
        // Single state boxes initialized with empty array
        // it contains all the created boxes and their properties
        this.state = { boxes : [] }
        this.createBox = this.createBox.bind(this)
      }
      
      // create new box and added it to boxes state
      createBox(attrs){
        const newBox = { ...attrs, id : uuid()}
        this.setState({
          boxes : [...this.state.boxes, newBox]
        })
      }
      
      // Map over each box in boxes state and render a 
      // Box component for each passing its property as
      // props and method is also passed as props which gets 
      // called by the handler callback of Box component
      renderBoxes(){
        return this.state.boxes.map(box => (
          
        ))
      }
        
      render(){
        return(
          
            

    Make New Color Boxes!

            {/* component to create form               and passes create method as */}                  {this.renderBoxes()}       
        )   } }    export default BoxList


    Javascript
    import React,{ Component } from 'react'
      
    class NewBoxForm extends Component{
      constructor(props){
        super(props)
        this.state = { height : 0, width : 0, bc : ''}
        this.handleChange = this.handleChange.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this)
      }
      
      // Form submitting logic, prevent default page 
      // refresh and call create method of BoxList
      // component to create new box
      handleSubmit(event){
        event.preventDefault()
        this.props.create(this.state)
        this.setState({ height : 0, width : 0, bc : ''})
      }
      
      // Method causes to store all the values of the 
      // input field in react state using single method 
      // handleChanges of all the input field
      // using ES6 javascript feature computed property names
      handleChange(event){
        this.setState({
          [event.target.name] : event.target.value
        })
      }
      
      // return a form using which we add box properties 
      // to create Boxes. It is controlled form i.e. values 
      // of the input field not stored in DOM values are exist
      // in react component itself as state
      
      render(){
        return(
          
            
                                  
            
                                  
            
                                  
            
                       
          
        )   } }    export default NewBoxForm


    Javascript
    import React, { Component } from 'react'
      
    class Box extends Component {
      render(){
        const { height, width, bc } = this.props.attrs
        const style = { width: `${width}em`, height:`${height}em`, backgroundColor:bc}
        return(
          
        )   } }    export default Box


  • App.js : App 组件仅呈现单个 Form 组件

    Javascript

    import React from 'react'
    import Form from './Form'
      
    //Functional component
    const App = () => {
      //render single App component
      return(
        
      ) }    export default App
  • Form.js:表单组件呈现表单并包含使其控制表单和提交表单的所有逻辑。

    Javascript

    import React,{ Component } from 'react'
      
    class Form extends Component{
      constructor(props){
        super(props)
        this.state = { email:'',name:'', age:null, address:'',phoneNo:''}
        this.handleChange = this.handleChange.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this)
      }
      
      // Form submitting logic, prevent default page refresh 
      handleSubmit(event){
        const { email, name, age, address, phoneNo } = this.state
        event.preventDefault()
        alert(`
          ____Your Details____\n
          Email : ${email}
          Name : ${name}
          Age : ${age}
          Address : ${address}
          Phone No : ${phoneNo}
        `)
      }
      
      // Method causes to store all the values of the 
      // input field in react state single method handle 
      // input changes of all the input field using ES6 
      // javascript feature computed property names
      handleChange(event){
        this.setState({
          // Computed property names
          // keys of the objects are computed dynamically
          [event.target.name] : event.target.value
        })
      }
      
      // Return a controlled form i.e. values of the 
      // input field not stored in DOM values are exist 
      // in react component itself as state
      render(){
        return(
          
            
                                  
            
                                  
            
                                  
            
                                  
            
                                  
            
                       
               )   } }    export default Form

输出 :

示例 2:

  • index.js:

    Javascript

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'
      
    ReactDOM.render(, document.querySelector('#root'))
    
  • App.js: App 组件仅呈现单个 BoxList 组件

    Javascript

    import React from 'react';
    import BoxList from './BoxList'
      
    const App = () => {
      //App renders single BoxList component
      return(
        
      )
    }
      
    export default App
    
  • BoxList.js:它包含了所有背后的逻辑。它是一个有状态的组件。有一个状态包含一组框。我们映射每个状态“盒子”盒子,并为每个盒子渲染一个“盒子”组件。 BoxList 组件还包含方法 create 负责根据给定属性创建框。 BoxComponent 还呈现“NewBoxForm”,向用户显示表单以输入他们想要创建的框的高度、宽度和背景颜色。 BoxList 组件将 create 方法作为道具传递给 NewBoxForm 组件,并将每个“Box”组件作为道具传递。然后根据用户与应用程序的交互,在正确的时间调用这些组件。

    Javascript

    import React, { Component } from 'react'
    import { v4 as uuid } from 'uuid'
    import NewBoxForm from './NewBoxForm'
    import Box from './Box'
      
    class BoxList extends Component{
      constructor(props){
        super(props)
        // Single state boxes initialized with empty array
        // it contains all the created boxes and their properties
        this.state = { boxes : [] }
        this.createBox = this.createBox.bind(this)
      }
      
      // create new box and added it to boxes state
      createBox(attrs){
        const newBox = { ...attrs, id : uuid()}
        this.setState({
          boxes : [...this.state.boxes, newBox]
        })
      }
      
      // Map over each box in boxes state and render a 
      // Box component for each passing its property as
      // props and method is also passed as props which gets 
      // called by the handler callback of Box component
      renderBoxes(){
        return this.state.boxes.map(box => (
          
        ))
      }
        
      render(){
        return(
          
            

    Make New Color Boxes!

            {/* component to create form               and passes create method as */}                  {this.renderBoxes()}       
        )   } }    export default BoxList
  • NewBoxForm.js:该组件负责向用户展示表单以输入他们想要创建的框的属性。表单是一种受控表单,即它以状态存储输入字段的值,并根据用户与表单输入字段的交互实时更新它。它在提交表单后调用句柄提交回调,该回调调用 BoxList 组件的 create 方法,传递表单值以创建框。

    Javascript

    import React,{ Component } from 'react'
      
    class NewBoxForm extends Component{
      constructor(props){
        super(props)
        this.state = { height : 0, width : 0, bc : ''}
        this.handleChange = this.handleChange.bind(this)
        this.handleSubmit = this.handleSubmit.bind(this)
      }
      
      // Form submitting logic, prevent default page 
      // refresh and call create method of BoxList
      // component to create new box
      handleSubmit(event){
        event.preventDefault()
        this.props.create(this.state)
        this.setState({ height : 0, width : 0, bc : ''})
      }
      
      // Method causes to store all the values of the 
      // input field in react state using single method 
      // handleChanges of all the input field
      // using ES6 javascript feature computed property names
      handleChange(event){
        this.setState({
          [event.target.name] : event.target.value
        })
      }
      
      // return a form using which we add box properties 
      // to create Boxes. It is controlled form i.e. values 
      // of the input field not stored in DOM values are exist
      // in react component itself as state
      
      render(){
        return(
          
            
                                  
            
                                  
            
                                  
            
                       
          
        )   } }    export default NewBoxForm
  • Box.js:它负责在背景中显示具有适当高度、宽度和颜色的每个框。

    Javascript

    import React, { Component } from 'react'
      
    class Box extends Component {
      render(){
        const { height, width, bc } = this.props.attrs
        const style = { width: `${width}em`, height:`${height}em`, backgroundColor:bc}
        return(
          
        )   } }    export default Box

输出 :