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

问题描述 投票:0回答:1

我有一个表单,默认情况下禁用保存按钮状态。当 2 个文本字段有值时,我会切换状态。在同一表单的另一个实例中,当编辑方法打开带有值的表单时,我希望按钮状态不被禁用。

注意我也在使用 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}
    />
  );
};

react-native redux styled-components
1个回答
0
投票

一种方法是使用

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>
);
© www.soinside.com 2019 - 2024. All rights reserved.