首页 > 解决方案 > 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 });
}

先感谢您。

标签: javascriptreactjstypescript

解决方案


问题在于您的以下代码。根据此代码,您的状态将是{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


推荐阅读