redux ReactNative如何在编辑表单被填充时删除按钮禁用状态

ggazkfy8  于 2023-11-19  发布在  React
关注(0)|答案(1)|浏览(112)

我有一个表单,默认情况下我禁用了保存按钮状态。当2个textField有一个值时,我切换状态。在同一表单的另一个示例中,当edit方法打开带有值的表单时,我希望按钮状态不被禁用。
注意我也在使用Redux。
这是添加的表格。

const MyForm = ({ navigation, ...props }) => {
  const [isDisabled, setIsDisabled] = useState(true);

  const handlePrice = (enteredPrice) => {
    setPrice(enteredPrice);
    isValueEntered(enteredPrice, windowType);
  };

  const handleType = (enteredText) => {
    setWindowType(enteredText);
    isValueEntered(price, enteredText);
  };
  // This is where disabled is toggled for save button
  const isValueEntered = (priceSet, type) => {
    if (priceSet != 0 && type.length > 1) {
      setIsDisabled(false);
    }
  };

  const handleSubmit = () => {
    props.onFormSubmit({
      id: props.id,
      windowType,
      price,
    });
    setWindowType('');
    setPrice(0);
    // other values
  };

  return (
    <FormWrapper>
      // ....
      <Button
        title="Save"
        onPress={() => handleSubmit()}
        disabled={isDisabled ? true : false}
      ></Button>
      <StyledInput
        placeholder={'Window Type'}
        color={'black'}
        onChangeText={handleType}
        value={windowType}
        width={'175px'}
      />
      <StyledInput
        width={'65px'}
        color={'black'}
        onChangeText={handlePrice}
        value={`${price}`}
        keyboardType="decimal-pad"
        returnKeyType="done"
      />
      // ...
    </FormWrapper>
  );
};

字符串
下面是我的编辑表单示例的样子。

const EditableCounter = (props) => {
  const [isOpen, setIsOpen] = useState(false);

  const handleEditClick = () => {
    setIsOpen(true);
  };

  const handleFormClose = () => {
    closeForm();
  };

  const closeForm = () => {
    setIsOpen(false);
  };

  const handleSubmit = (counter) => {
    props.onFormSubmit(counter);
    closeForm();
  };

  return isOpen ? (
    <MyForm
      key={props.counter.item.id}
      id={props.counter.item.id}
      windowType={props.counter.item.windowType}
      price={props.counter.item.price}
      onFormClose={handleFormClose}
      onFormSubmit={handleSubmit}
    />
  ) : (
    <Counter
      key={props.counter.item.id}
      counter={props.counter.item}
      onFormClose={handleFormClose}
      onEditClick={handleEditClick}
    />
  );
};

lb3vh1jj

lb3vh1jj1#

一种方法是使用useEffect钩子,表单字段作为依赖项。当任何依赖项更改时,再次验证表单。类似于以下内容:

const [isDisabled, setIsDisabled] = useState(true);

useEffect(() => {
  setIsDisabled(text.length < 1)
}, [text])

return (
  <View>
    <TextInput onChangeText={setText} value={text} />
    <Button title="Save" disabled={isDisabled} />
  </View>
);

字符串

相关问题