Text Box coming disabled in React JS using Type Script

老子叫甜甜 提交于 2019-12-11 05:08:01

问题


I have used TSX file for loading text box in React JS as below :

<input type={'text'} value={employees.length > 0 ? employees[0].name : ""} id=
{'Name'} label={'Name'} name={'Name'} htmlFor={'Name'} />

Now when I load this file then we cant write any thing in text box.

So anyone can please help me?


回答1:


You cannot write anything because you have created a controlled component which means that the value of the input will always be whatever the value prop evaluates to - in this case employees[0].name or "".

With some minor adjustments you can make this work, either by making it a controlled component with an event listener which updates the value, or by making it an uncontrolled component.

In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.

More info here and here.


Option 1 - Controlled component (recommended)

To make a controlled component, you need to add the onChange event listener and have that update the variable that you pass into value. It's not clear from your question what employees is; if it's a state or prop variable or something else.

Assuming it's a state variable, you can do:

handleChange = (e) => {
  let arr = this.state.employees.slice();
  arr[0].name = e.target.value;
  this.setState({employees: arr});
}

render() {
  let {employees} = this.state;
  return (
    <input type={'text'} onChange={this.handleChange} value={employees.length > 0 ? employees[0].name : ""} id={'Name'} label={'Name'} name={'Name'} htmlFor={'Name'} />
  );
}

Option 2 - Uncontrolled component

You only need a slight modification to make your input an uncontrolled component. Simply replace value with defaultValue:

<input type={'text'} defaultValue={employees.length > 0 ? employees[0].name : ""} id={'Name'} label={'Name'} name={'Name'} htmlFor={'Name'} />

As a side note, you don't need to wrap string literals in brackets. So instead of <input type={'text'} ... you can just do <input type='text' ..., if you prefer.



来源:https://stackoverflow.com/questions/46219828/text-box-coming-disabled-in-react-js-using-type-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!