简体   繁体   中英

How to access function component's state variables in ReactJS?

I've been developing a website and I'm faced with an issue about accessing state varibles to a component. I've a address page(Addresses.jsx file) which has address modal. I'm also have a component which contains address modal's content (Address.jsx). I would like to access state inside Address.jsx file. How can I do that? If you can help me. I would be very appreciate.

Here is my code blocks;

Address.jsx file;

const Addresses = () => {
const [selectedAddress, setSelectedAddress] = useState();
const [modalType, setModalType] = useState();
const {
  elementRef: addressModalRef,
  show: showAddressModal,
  hide: hideAddressModal,
} = useModal();

return (
  <>
    <div className="bg-light px-3 px-lg-4 py-4">
    <h1 className="h4 mb-4">My Addresses</h1>
    <div className="row g-3">
      <div className="col-12 col-md-6 col-lg-4">
        <AddressButton
          onClick={() => {
            setSelectedAddress(undefined);
            setModalType("NewAddress");
            showAddressModal();
          }}
        />
      </div>
      {ADDRESSES.map((address, i) => (
        <div className="col-12 col-md-6 col-lg-4" key={i}>
          <AddressButton
            {...address}
            onClick={() => {
              setSelectedAddress(address);
              setModalType("EditAddress");
              showAddressModal();
            }}
          />
        </div>
      ))}
    </div>
  </div>

  <AddressModal
    address={selectedAddress}
    elementRef={addressModalRef}
    hide={hideAddressModal}
    modalType={modalType}
  />
</>)};
export default Addresses;

Address Modal file;

const AddressModal = ({ address, elementRef, hide, modalType }) => {
const onSaveAddress = () => {
  console.log(address);
  hide();
};
return (
<Modal elementRef={elementRef} centered size="lg" fullscreen>
  <ModalBody>
    <AddressForm address={address} /> // I would like to get this component's state in onSaveAddress funtion
  </ModalBody>
  <ModalFooter>
    <button
      type="button"
      className="btn btn-primary flex-grow-1 px-5"
      onClick={onSaveAddress}>
      Kaydet
    </button>
  </ModalFooter>
</Modal>)};
export default AddressModal;

Instead of accessing child components state, which is not possible, do the following

Address Model

<AddressForm 
    address={address} 
    onSave={onSaveAddress} 
/> 

Address Form

const AddressForm = ({ onSave }) => {
  const handleFormSubmit = () => {
    onSave(formData);
  };

  return (
    <form onSubmit={handleFormSubmit}>

    </form>
  );
}

Then in onSaveAddress , you will have access to the form data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM