javascript - 如何在 reactjs 事件期间禁用和启用文本字段?
问题描述
我正在尝试使用 ReactJS 禁用和启用文本字段。
场景是:
- 使用输入文本并点击回车
- 必须禁用文本字段以防止输入新数据
- 文本被发送到服务器保存
- 保存后必须再次启用文本框。
问题是setState
在 ReactJS 中的单个事件期间通过函数更新字段两次是不可能的,因为它只在完成相关事件后更新一次。那么,如何在事件期间更新输入字段两次?
我也尝试this.forceUpdate()
在 each 之后使用this.setState(...)
,但它没有用。
theEvent(e){
if(e.key==='Enter'){
this.setState({newTypePredefinedValue: ''});
this.setState({readOnly:true})
this.forceUpdate();
fetch(..., { ... })
.then(() => this.componentDidMount() )
.then(this.setState({readOnly:false}))
.then(this.forceUpdate());
}
}
我正在寻找一种在活动期间禁用和启用所需字段的方法。
解决方案
请注意,您正在使用
.then(this.setState({readOnly:false}))
代替
.then(() => this.setState({readOnly:false}))
这会导致第二个setState
被立即调用,而不是在响应到达并且您处理它时。
你也不应该打电话forceUpdate
。
示例场景
class Element extends React.Component {
constructor(props) {
super(props);
this.state = {
readOnly: false,
input: '',
}
this.handleFetch = this.handleFetch.bind(this);
this.handleInput = this.handleInput.bind(this);
}
handleInput(e) {
this.setState({
input: e.target.value
});
}
handleFetch(e) {
e.preventDefault();
this.setState({
readOnly: true
});
setTimeout(() => {
this.setState({
readOnly: false
})
}, 4000);
/* You should use in your actual code
fetch(..., { ... })
.then(res => {
// Handle response
this.setState({
readOnly:false
})
});
*/
}
render() {
return (
<div>
<button onClick={this.handleFetch}>Click me!</button>
<input type="text" disabled={this.state.readOnly} />
</div>
)
}
}
您的函数代码已重写,如示例代码所示。
theEvent(e){
if(e.key === 'Enter') {
this.setState({
newTypePredefinedValue: '',
readOnly:true
});
fetch(..., { ... })
.then(res => {
// Handle response
this.setState({
readOnly:false
})
});
}
}
推荐阅读
- javascript - 如何为两个独立的功能设置本地存储(暗光模式)
- python-3.x - 在训练数据上运行模型后如何将逻辑回归应用于测试数据
- apache-spark - PySpark 上传到在 Databricks 上运行的 S3 的速度极慢
- templates - 比较(别名)模板模板
- c - 约瑟夫斯问题归一化方程的误差
- mysql - 在mysql中的表中存储200个字段的最佳有效方法
- php - 如何从第二个表中打印出我的所有数据
- c++ - 如何修复我的输出的无限循环?
- javascript - Larvel 5.8:从 javascript 但不是从浏览器调用路由时忽略中间件
- java - 在 JDK 1.8 中导入项目时出现 jaxb2-maven-plugin 问题