javascript - React.JS Typescript - OnChange 表示状态对象的“组件正在将类型文本的受控输入更改为在 OnChange 中不受控制”
问题描述
再会,
我是新手,react.js
我正在尝试使用onChange
输入创建基本数据绑定。问题是,我用它的属性分配给对象。不直接到物业。
现在,Warning: A component is changing a controlled input of type text to be uncontrolled.
当我在输入中输入字符时收到错误消息。
这是我的代码:
interface IProps { }
interface IFloorInfo {
id: number
name: string,
type: string,
condition: string
}
interface IFloorInfoState {
floor: IFloorInfo
}
export default class Floors extends React.Component<IProps, IFloorInfoState> {
state: IFloorInfoState
constructor(props: any){
super(props)
this.state = {
floor: {
id: 0,
name: '',
type: '',
condition: ''
}
}
}
...
render() {
return (
<div>
<input type="text" value={this.state.floor.name} onChange={(e)=>this.inputChanges(e)} />
<input type="text" value={this.state.floor.type} onChange={(e)=>this.inputChanges(e)} />
<input type="text" value={this.state.floor.condition} onChange={(e)=>this.inputChanges(e)} />
</div>
)
}
}
现在这是我的inputChanges
方法来检测是否有变化input
inputChanges = (e:any) => {
this.setState({ floor: e.target.value });
}
先感谢您。
解决方案
问题在于您的以下代码。根据此代码,您的状态将是{floor: "input value"}
inputChanges = (e:any) => {
this.setState({ floor: e.target.value });
}
但你真正想要的是
inputChanges = (e:any) => {
// copying all values of floor from current state;
var currentFloorState = {...this.state.floor};
// setting the current input value from user
var name = e.target.name;
currentFloorState[name] = e.target.value;
this.setState({ floor: currentFloorState });
}
至于多个属性:您可以将 name 属性添加到您的元素并在您的changeHandler
render() {
return (
<div>
<input type="text" value={this.state.floor.name} name="floor" onChange={(e)=>this.inputChanges(e)} />
<input type="text" value={this.state.floor.type} name="type" onChange={(e)=>this.inputChanges(e)} />
</div>
)
}
对于演示,您可以参考此https://codesandbox.io/s/jolly-ritchie-e1z52
推荐阅读
- python - 递归提取href链接
- excel - 根据条件显示值
- r - 在同一条曲线中绘制不同的混合模型簇
- visual-studio-code - 在 vscode 中打开的文件之间跳转
- c# - 如何在没有 SecureString 的情况下保护字符串?
- javascript - 使用 JavaScript 重置输入不起作用
- deep-learning - STB原因:打不开
- .net - 鼠标左键单击未与弹出 wpf 中的列表框绑定
- airflow - 气流自定义传感器:AttributeError:“NoneType”对象没有属性“get_records”
- shell - 如何删除带有特殊字符的文件