本文介绍了如何编辑React中的多个输入受控组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个将联系对象存储为状态的组件 - {firstName:John,lastName:Doe,phone:1234567890}我想创建一个表单来编辑此对象,但如果我想要输入保持原始联系人参数的值,我需要使每个输入都是一个受控组件。但是,我不知道如何创建一个handleChange函数来调整每个参数,因为我的状态只包含{contact:{...下面是我现在有的 - $ / $>

  getInitialState:function(){
return({contact:{} }});
},
handleChange:function(event){
this.setState({contact:event.target.value});
},
render:function(){
return(
< div>
< input type =textonChange = {this.handleChange} value = {this.state.contact.firstName} />
< input type =textonChange = {this.handleChange} value = {this.state.contact.lastName} />
< input type =text onChange = {this.handleChange} value = {this.state.contact.lastName} />
< / div>
);
}

我希望在我的handleChange中可以做类似于

  handleChange:function(event){
this.setState({contact.firstName:event.target.value});
}


解决方案

做到这一点,以及聪明的方式。如果你问我,聪明的做法并不总是最好的,因为我以后可能会更难。在这种情况下,两者都是可以理解的。



附注:我要求您考虑的一件事是,您是否需要更新联系对象,或者你可以直接在状态下保留 firstName 等。也许你在组件状态下有很多数据?如果是这样的话,将它分成更小的组件可能是个好主意。



简单方式



  changeFirstName:function(event){
const contact = this.state.contact;
contact.firstName = event.target.value;
this.setState({contact:contact});
},
changeLastName:function(event){
const contact = this.state.contact;
contact.lastName = event.target.value;
this.setState({contact:contact});
},
changePhone:function(event){
const contact = this.state.contact;
contact.phone = event.target.value;
this.setState({contact:contact});
},
render:function(){
return(
< div>
< input type =textonChange = {this.changeFirstName.bind (this)} value = {this.state.contact.firstName} />
< input type =textonChange = {this.changeLastName.bind(this)} value = {this.state.contact .lastName} />
< input type =textonChange = {this.changePhone.bind(this)} value = {this.state.contact.phone} />
< / div>
);



智能方式



  handleChange:function(propertyName,event){
const contact = this.state.contact;
联系[propertyName] = event.target.value;
this.setState({contact:contact});
},
render:function(){
return(
< div>
< input type =textonChange = {this.handleChange.bind (this,'firstName')} value = {this.state.contact.firstName} />
< input type =textonChange = {this.handleChange.bind(this,'lastName')} value = {this.state.contact.lastName} />
< input type =textonChange = {this.handleChange.bind(this,'phone')} value = {this.state.contact .lastName} />
< / div>
);
}






更新:使用ES2015 +的相同示例



本节包含与上述示例相同的示例,但使用ES2015 + p>

为了支持跨浏览器的以下功能,您需要使用和,
和插件。



以下是更新的示例,使用从状态获取联系人,

创建一个更新的联系人对象,而不是改变现有的
将组件创建为 by
扩展,
并使用到
创建回调函数,所以我们不需要 bind(this)



简单方式, ES2015 +



class ContactEdit extends React.Component {

changeFirstName =(event)=> {
const {contact} = this.state;
const newContact = {
... contact,
firstName:event.target.value
};
this.setState({contact:newContact});
}
changeLastName =(event)=> {
const {contact} = this.state;
const newContact = {
... contact,
lastName:event.target.value
};
this.setState({contact:newContact});
}
changePhone =(event)=> {
const {contact} = this.state;
const newContact = {
... contact,
phone:event.target.value
};
this.setState({contact:newContact});




$ b $ lt; div>
< input type =textonChange = {this.changeFirstName} value = {this.state.contact.firstName} />
< input type =textonChange = {this.changeLastName} value = {this.state.contact.lastName} />
< input type =textonChange = {this.changePhone} value = {this.state.contact.phone} />
< / div>
);




$ b

智能方式,ES2015 +



请注意, handleChangeFor 是一个:
使用 propertyName 调用它会创建一个回调函数,
(新)联系人对象的code> [propertyName]

  class ContactEdit extends React.Component {

handleChangeFor =(propertyName)=> (event)=> {
const {contact} = this.state;
const newContact = {
... contact,
[propertyName]:event.target.value
};
this.setState({contact:newContact});

$ b $ render b


$ lt; div>
< input type =textonChange = {this.handleChangeFor( 'firstName')} value = {this.state.contact.firstName} />
< input type =textonChange = {this.handleChangeFor('lastName')} value = {this.state。 contact.lastName} />
< input type =textonChange = {this.handleChangeFor('phone')} value = {this.state.contact.lastName} />
< ; / div>
);
}
}


I have a component that stores a contact object as state - {firstName: "John", lastName: "Doe", phone: "1234567890} I want to create a form to edit this object but if I want the inputs to hold the value of the original contact parameter, I need to make each input a controlled component. However, I don't know how to create a handleChange function that will adjust to each parameter because my state only holds {contact: {...}}. Below is what I currently have -

  getInitialState: function () {
    return ({contact: {}});
  },
  handleChange: function (event) {
    this.setState({contact: event.target.value });
  },
  render: function () {
    return (
        <div>
          <input type="text" onChange={this.handleChange} value={this.state.contact.firstName}/>
          <input type="text" onChange={this.handleChange} value={this.state.contact.lastName}/>
          <input type="text" onChange={this.handleChange} value={this.state.contact.lastName}/>
        </div>
      );
    }

I wish in my handleChange I can do something like

  handleChange: function (event) {
    this.setState({contact.firstName: event.target.value });
  }
解决方案

There's a "simple" way to do this, and a "smart" way. If you ask me, doing things the smart way is not always the best, because I may be harder to work with later. In this case, both are quite understandable.

Side note: One thing I'd ask you to think about, is do you need to update the contact object, or could you just keep firstName etc. directly on state? Maybe you have a lot of data in the state of the component? If that is the case, it's probably a good idea to separate it into smaller components with narrower responsibilities.

The "simple" way

  changeFirstName: function (event) {
    const contact = this.state.contact;
    contact.firstName = event.target.value;
    this.setState({ contact: contact });
  },
  changeLastName: function (event) {
    const contact = this.state.contact;
    contact.lastName = event.target.value;
    this.setState({ contact: contact });
  },
  changePhone: function (event) {
    const contact = this.state.contact;
    contact.phone = event.target.value;
    this.setState({ contact: contact });
  },
  render: function () {
    return (
      <div>
        <input type="text" onChange={this.changeFirstName.bind(this)} value={this.state.contact.firstName}/>
        <input type="text" onChange={this.changeLastName.bind(this)} value={this.state.contact.lastName}/>
        <input type="text" onChange={this.changePhone.bind(this)} value={this.state.contact.phone}/>
      </div>
    );
  }

The "smart" way

  handleChange: function (propertyName, event) {
    const contact = this.state.contact;
    contact[propertyName] = event.target.value;
    this.setState({ contact: contact });
  },
  render: function () {
    return (
      <div>
        <input type="text" onChange={this.handleChange.bind(this, 'firstName')} value={this.state.contact.firstName}/>
        <input type="text" onChange={this.handleChange.bind(this, 'lastName')} value={this.state.contact.lastName}/>
        <input type="text" onChange={this.handleChange.bind(this, 'phone')} value={this.state.contact.lastName}/>
      </div>
    );
  }



Update: Same examples using ES2015+

This section contains the same examples as shown above, but using features from ES2015+.

To support the following features across browsers you need to transpile your code with Babel using e.g.the presets es2015 and react,and the plugin stage-0.

Below are updated examples, using object destructuring to get the contact from the state,spread operator tocreate an updated contact object instead of mutating the existing one,creating components as Classes byextending React.Component,and using arrow funtions tocreate callbacks so we don't have to bind(this).

The "simple" way, ES2015+

class ContactEdit extends React.Component {

  changeFirstName = (event) => {
    const { contact } = this.state;
    const newContact = {
      ...contact,
      firstName: event.target.value
    };
    this.setState({ contact: newContact });
  }
  changeLastName = (event) => {
    const { contact } = this.state;
    const newContact = {
      ...contact,
      lastName: event.target.value
    };
    this.setState({ contact: newContact });
  }
  changePhone = (event) => {
    const { contact } = this.state;
    const newContact = {
      ...contact,
      phone: event.target.value
    };
    this.setState({ contact: newContact });
  }

  render() {
    return (
      <div>
        <input type="text" onChange={this.changeFirstName} value={this.state.contact.firstName}/>
        <input type="text" onChange={this.changeLastName} value={this.state.contact.lastName}/>
        <input type="text" onChange={this.changePhone} value={this.state.contact.phone}/>
      </div>
    );
  }
}

The "smart" way, ES2015+

Note that handleChangeFor is a curried function:Calling it with a propertyName creates a callback function which, when called, updates [propertyName] of the(new) contact object in the state.

class ContactEdit extends React.Component {

  handleChangeFor = (propertyName) => (event) => {
    const { contact } = this.state;
    const newContact = {
      ...contact,
      [propertyName]: event.target.value
    };
    this.setState({ contact: newContact });
  }

  render() {
    return (
      <div>
        <input type="text" onChange={this.handleChangeFor('firstName')} value={this.state.contact.firstName}/>
        <input type="text" onChange={this.handleChangeFor('lastName')} value={this.state.contact.lastName}/>
        <input type="text" onChange={this.handleChangeFor('phone')} value={this.state.contact.lastName}/>
      </div>
    );
  }
}

这篇关于如何编辑React中的多个输入受控组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 13:11