Text Box coming disabled in React JS using Type Sc

2019-08-04 06:29发布

问题:

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.