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

时间:2019-06-18 05:38:35

标签: 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>
);

下面是我的TextFieldWithValidation代码。

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

下面是我的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>
  );
};

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

2 个答案:

答案 0 :(得分:1)

Yu在onChange组件中将EditStyleFormComponent定义为空字符串。因此,在任何更改输入组件上什么都不做。

onChange应该是一些可以更新值的功能。

如果要使用功能组件,则有两种可能的解决方案:

  1. Lift state upEditStyleFormComponent的父级组件(如果父级是基于类的组件)

  2. 像这样使用React Hooks(只是示例!)

    const EditStyleFormComponent = ({
        submitting,
        invalid,
    }) => {
        const [inputValue, setInputValue] = useState ('Current'); // default value goes here
        return <form className={className} onSubmit={handleSubmit}>
            <h2>LSPL (Low Stock Presentation Level)</h2>
            <Line />
            <InputGroup>
                <TextFieldWithValidation name="lsplMan" label="LSPL Manual" input={{ onChnage: (e) => { setInputValue(e.target.value); }, value: inputValue }} />
            </InputGroup>
        </form>
    };
    

答案 1 :(得分:0)

您可以使用状态挂钩来管理功能组件中的状态。 示例:

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>
  );
};
相关问题