簡體   English   中英

如何在其中包含所有組件邏輯並將其導出到父組件

[英]How to have all component logic inside of it and export it to parent components

我有一個模態組件,用於為用戶顯示表單。 此模態接受三個參數:is_visible(如果顯示模態)、toggleModal(狀態 function 用於管理模態是否顯示)、passport_id(此處不相關)。 該組件在另一個組件中使用,即下面的護照組件。 This passport component is where the state that manages the visibility of modal is created, and then, as said above, the state function and state variable are passed down to the modal (child component).

這很好用,但是在其父級上定義模態的部分功能似乎是錯誤的。 我相信控制模態是否顯示的state應該在模態組件內部定義,然后,如果有必要在模態之外使用這些功能,它們應該被導出。 我已經通過在模態中定義一個鈎子並導出到護照組件來嘗試這個,但它沒有工作,因為模態內的 state 變量沒有更新。

所以我的問題是是否有適當的方法來應用“告訴,不要問”( https://martinfowler.com/bliki/TellDontAsk.html )的想法,從而可以告訴組件做某事傳遞數據。 或者,換句話說,把modal的邏輯放在modal組件里面

模態組件:

const TransferPassportModal = ({is_visible, toggleModal, passport_id}) => {
  const [input_text, setInputText] = useState(''),
    [loading, setLoading] = useState(false);

  function closeModal() {
    toggleModal(false);
  }

  return (
    <Modal animationType="fade" transparent={true} visible={is_visible}>
      <View style={styles.modal}>
        <View style={styles.modal_content}>
          <TouchableOpacity
            onPress={closeModal}
            style={styles.close_modal_button}>
            <Icons name="close" size={20} />
          </TouchableOpacity>
          // Rest of code
        </View>
      </View>
    </Modal>
  );
};

export default TransferPassportModal;

護照組件:

 const Passport = ({passport}) => {
  const [toggleModal, setToggleModal] = useState(false);

  function openModal() {
    setToggleModal(!toggleModal);
  }

  return (
    <View style={styles.wrapper}>
      <View style={styles.infos_wrapper}>
        <Text style={styles.name}>{passport.nome}</Text>
        <Text style={styles.text}>{passport.codigo}</Text>
      </View>
      <View style={styles.buttons_wrapper}>
        // Resto of code
        <TransferPassportModal
          is_visible={toggleModal}
          passport_id={passport.ingresso}
          toggleModal={setToggleModal}
        />
      </View>
    </View>
  );
};

export default Passport;

我最近這樣做:

export const OpenModalAction = () =>{
  return (
     <>
        <Button/>
        <Modal> …. <Modal/>
     </>
  )
}

所以按鈕和模態是一個組件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM