javascript - 反应中的 onChange
问题描述
我无法用 更新我的customerContact
状态handleChange
。事实上,我使用该updateContact
功能来检索客户的 ID,以便能够修改他们的联系方式。但是,当我得到 id 时,我觉得我正在阻止状态更新。所以我无法编辑联系人字段。
有人可以帮我吗?
class DetailsCustomer extends React.Component{
constructor (props) {
super(props)
this.handleChange = this.handleChange.bind(this);
this.toggle = this.toggle.bind(this);
this.toggle1 = this.toggle1.bind(this);
this.state = {
id: props.match.params,
customers: [],
customerContact: {},
customerContacts: [],
customerAddresses: [],
genders: [],
contactTypes: [],
addressTypes: [],
};
}
updateContact = (id, index) => {
this.setState({
customerContact: this.state.customerContacts[index],
}, () => {
console.log("update-contact: ", this.state.customerContact);
})
handleChange = async ({currentTarget}) => {
const {name, value} = currentTarget;
this.setState({...this.customerContact, [name]: value});
}
render() {
const { id, customerContacts, customerContact, genders, name } = this.state;
return(
<div className="form-group col-md-12">
<Field name="lastName" label="Nom" placeholder="Nom" value=
{this.state.customerContact.lastName} onChange={this.handleChange.bind(this)} />
</div>
)}
字段.jsx
import React from 'react';
const Field = ({name, label, value, onChange, placeholder = "", type = "text", error = "" }) => (
<div className="form-group">
<label htmlFor={name}>{label}</label>
<input
value={value}
onChange={onChange}
type={type}
placeholder={placeholder || label}
name={name}
id={name}
className={"form-control" + (error && " is-invalid")}
/>
{error && <p className="invalid-feedback">{error}</p> }
</div>
);
export default Field;
解决方案
你说handleChange需要得到一个对象,但是当你调用handleChange时你没有给它。我认为这可能会有所帮助。如果你使用箭头函数 => 你不需要在函数上使用 this.bind
class DetailsCustomer extends React.Component{
constructor (props) {
super(props)
this.toggle = this.toggle.bind(this);
this.toggle1 = this.toggle1.bind(this);
this.state = {
id: props.match.params,
customers: [],
customerContact: {},
customerContacts: [],
customerAddresses: [],
genders: [],
contactTypes: [],
addressTypes: [],
};
}
updateContact = (id, index) => {
this.setState({
customerContact: this.state.customerContacts[index],
}, () => {
console.log("update-contact: ", this.state.customerContact);
})
handleChange = async (e) => {
this.setState({customerContact: e.target.value});
}
render() {
const { id, customerContacts, customerContact, genders, name } = this.state;
return(
<div className="form-group col-md-12">
<Field name="lastName" label="Nom" placeholder="Nom" value=
{this.state.customerContact} onChange={(e)=>this.handleChange(e)} />
</div>
)}
推荐阅读
- r - 需要帮助使用“Imager”包进行灰度化:灰度错误(im):图像应具有三个颜色通道
- python - 如何删除每个组的多索引数据框中的第一行?
- html - 不小心保存了源html而不是原始html
- javascript - 不确定如何在 JavaScript 中使用反引号
- ios - 下载多个文件,操作队列在后台模式下不稳定
- typescript - 打字稿中的单元测试vuex动作,如何传递这个值?
- javascript - Angular 不适用于所有浏览器。它仅适用于 chrome
- javascript - React Native Navigation 中的全局组件
- javascript - 从 DOM 中移除/删除模板的函数
- php - 消息:未定义的属性:PHP7.3 Codeigniter 中的 MongoDB\Driver\Manager