更简洁的方法为具有许多影响嵌套状态属性的输入的表单编写onChange处理程序?

时间:2018-03-13 14:34:27

标签: reactjs

为多个输入编写handleChange函数的更紧凑,更简单的方法是:

import React from "react";

function initialState() {
  return ({
    customer: {
      name: '',
      primaryContactPerson: {
        name: '',
        email: ''
      }
    }
  })
}

export default class AddCustomerForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = initialState();

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event, field) {
    console.log(event.target.name);
    switch(event.target.name) {
      case 'customer.name':
        console.log(1);
        this.setState({
          this: {
            customer: {
              name: event.target.value
            }
          }
        })
        break;
      case 'customer.primaryContactPerson.name':
        console.log(2);
        this.setState({
          this: {
            customer: {
              primaryContactPerson: {
                name: event.target.value
              }
            }
          }
        })
        break;
      case 'customer.primaryContactPerson.email':
        this.setState({
          this: {
            customer: {
              primaryContactPerson: {
                email: event.target.value
              }
            }
          }
        })
        break;
      default:
        break;
    }
    this.setState({[event.target.name]: event.target.value});
  }

  render() {
    return (
      <div className='section section--full-width'>
        <h1>Add Customer</h1>
        <form onSubmit={this.handleSubmit}>
          <div className='form__row'>
            <label>
              Customer name
            </label>
            <input type="text" name="customer.name" value={this.state.customer.Name} onChange={this.handleChange} />
          </div>
          <div className='form__row'>
            <label>
              Contact person
            </label>
            <input type="text" name="customer.primaryContactPerson.name" value={this.state.customer.primaryContactPerson.name} onChange={this.handleChange} />
          </div>
          <div className='form__row'>
            <label>
              Contact details
            </label>
            <input type="text" name="customer.primaryContactPerson.email" value={this.state.customer.primaryContactPerson.email} onChange={this.handleChange} />
          </div>            
          <div>
            <input type="submit" value="Add" />
          </div>
        </form>
      </div>
    );
  }
}

我尝试了以下不适用于嵌套对象的方法:

handleChange(event, field) {
    this.SetState({event.targetname: event.target.value})
}

1 个答案:

答案 0 :(得分:2)

一个肮脏的黑客正在使用lodash from collections import OrderedDict titles = OrderedDict(( ('Karen', 'CEO'), ('Bob', 'CFO'), ('Jo', 'COO'), ('Steve', 'CIO') )) @click.command() @click.option('--name', cls=EnumMenuPromptFromDict, prompt=titles) def cli(name): """The Great CLI APP""" click.echo('a title: %s' % name) if __name__ == "__main__": print('Click Version: {}'.format(click.__version__)) print('Python Version: {}'.format(sys.version)) cli([]) Link。这不是推荐的方法,只是一种解决方法。

你可以使用

_.set

如果你想避免直接状态突变,你也可以使用

const tmp = this.state;
_.set(tmp, event.target.name, event.target.value);
this.setState({ customer: tmp.customer });

此过程将更慢