reactjs - React - 即使在我设置状态后输入字段也无法编辑
问题描述
我正在尝试输入输入,但它也不允许我输入。我的状态发生了变化,但没有显示。如果没有道具(未选择事件),我正在使用道具来显示事件或空事件。
抱歉,Stack 告诉我要添加更多详细信息,但我不知道还要添加什么,我已经描述了我的问题
class EventForm extends PureComponent {
state = {
event: this.props.selectedEvt,
query: ""
};
onFormSubmit = e => {
e.preventDefault();
this.props.addEvent(this.state.event);
};
onInputChange = evt => {
console.log(evt);
evt.persist();
let newEvt = this.state.event;
newEvt[evt.target.name] = evt.target.value;
this.setState({
event: newEvt
});
};
componentDidUpdate(prevProps) {
this.props.selectedEvt &&
this.setState({
event: this.props.selectedEvt
});
}
render() {
const { event } = this.state;
return (
<form className="card" onSubmit={this.onFormSubmit}>
<div className="form-row card-body">
<div className="form-group col-md-12">
<label hmtlfor="inputName">Event Name</label>
<input
name="title"
type="text"
className="form-control"
id="inputEventName"
onChange={this.onInputChange}
value={event.title}
/>
<label hmtlfor="inputDate">Event Date</label>
<input
name="date"
type="date"
className="form-control"
id="inputEventDate"
onChange={this.onInputChange}
value={event.date}
/>
<label hmtlfor="inputDate">Event Time</label>
<input
name="time"
type="time"
className="form-control"
id="inputEventTime"
onChange={this.onInputChange}
value={event.time}
/>
<label hmtlfor="inputAddress">Address</label>
<input
name="address"
type="text"
className="form-control"
id="autocomplete"
onChange={this.onInputChange}
value={event.address}
autoComplete="new-password"
/>
<label hmtlfor="inputHost">Hosted By</label>
<input
name="host"
type="text"
className="form-control"
id="inputHost"
onChange={this.onInputChange}
value={event.host}
/>
<label hmtlfor="inputDesc">Description</label>
<textarea
name="desc"
className="form-control"
rows="5"
id="inputDesc"
wrap="soft"
onChange={this.onInputChange}
value={event.description}
/>
<button type="submit" className="btn btn-primary mt-2">
Submit
</button>
</div>
</div>
</form>
);
}
}
export default EventForm;
解决方案
每次输入值更改 componentDidMount 运行并将状态重置为初始状态值componentDidUpdate
。
componentDidUpdate(prevProps) {
this.props.selectedEvt &&
this.setState({
event: this.props.selectedEvt // Here is the problem
});
}
当输入改变时你也会改变状态。并且因为它的 pureComponent 不会更新。
更改onInputChange
为
onInputChange = evt => {
let name = evt.target.name;
let value = evt.target.value;
let newEvent = {...this.state.event};
newEvent[name] = value
this.setState({event: newEvent});
}
推荐阅读
- java - 对 Lambda 对象的方法调用返回值
- perl - Perl - 使用带有编码 URL 的 Mojolicious::Plugin::OpenAPI
- python - 如何从具有唯一键和值的字典中创建数据框作为列表?
- javascript - 在 JS 中的 agGrid 中显示二维数组
- amazon-web-services - 我如何调试使用 AuthorizerConfigurationException 产生错误的 aws lambda 授权程序
- java - 如何确保多次单击单个按钮不会重复结果?
- javascript - React.JS 中的 jquery“this”选择器替换
- html - 如何解决 CSS 链接问题
- c# - GoogleOAuth2AuthenticationHandler + SSL 终止 - redirect_uri_mismatch
- javascript - Vue.js 中带有观察者的动画 Int 到 Int 变化