如何设置功能组件中文本框的状态

Nir*_*jan 2 reactjs

我正在研究 React JS。我有一个文本框组件,我想在其中显示一些默认值。之后,应允许用户更改该值。现在我无法更改该值。文本框的行为类似于只读。下面是我的代码

const EditStyleFormComponent = ({
submitting,
invalid,
}) => (
  <form className={className} onSubmit={handleSubmit}>
    <h2>LSPL (Low Stock Presentation Level)</h2>
    <Line />
    <InputGroup>
       <TextFieldWithValidation name="lsplMan" label="LSPL Manual" input={{ onChnage:'', value: 'Current' }} />
    </InputGroup>
 </form>
);
Run Code Online (Sandbox Code Playgroud)

下面是我的 TextFieldWithValidation 代码。

export const TextFieldWithValidationComponent = ({
  meta,
  input,
  noStyles,
  ...otherProps
}) => (
  <TextField
    state={noStyles ? textFieldStates.DEFAULT : getState(meta)}
    errorMessage={meta.touched ? meta.error : null}
    {...input}
    {...otherProps}
  />
);
Run Code Online (Sandbox Code Playgroud)

下面是我的 TextField 代码。

const TextField = ({
  className,
  label,
  description,
  state,
  errorMessage,
  isEditable,
  spaceAtBottom, // Not used, but we don't want it in otherProps
  ...otherProps
}) => {
  const inputId = _.uniqueId();

  return (
    <div className={className}>
      {label &&
        <label htmlFor={inputId}>{label}</label>
      }
      <div className="input-group" id={isEditable ? 'editable' : 'readonly'}>
        <input
          id={inputId}
          readOnly={!isEditable}
          {...otherProps}
        />
        {getStatusIcon(state)}
        {errorMessage &&
          <Error>{errorMessage}</Error>
        }
        {description &&
          <Description>{description}</Description>
        }
      </div>
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决这个问题吗?任何帮助,将不胜感激。谢谢

小智 8

您可以使用 State Hook 来管理功能组件中的状态。例子 :

const Message = () => {
  const [message, setMessage] = useState( '' );

  return (
    <div>
      <input
         type="text"
         value={message}
         placeholder="Enter a message"
         onChange={e => setMessage(e.target.value)}
       />
      <p>
        <strong>{message}</strong>
      </p>
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)