简体   繁体   中英

Can we access functions outside of stateless component in react?

Trying to invoke modal function from outside, but not possible. Achieved with class component using static method and properties, but this will not work there. Observers are giving some issues, finally landing to stateless component. How best way we can make this work?

//Inside
import Modal from './modal';
   // Not working
   <Button onClick={Modal.showModal}
<Modal />


//Outside

export const Modal = () => {
  const [visible, setVisible] = useState(false);

  const showModal = () => {
     setVisible(true);
  }
  return(
     <Dialog visible={visible}>Hello Test</h1>
  )
}

You can declare setVisible in parent component:

  const [visible, setVisible] = useState(true);

Then pass the set function to Modal:

 <Modal visible={visible} setVisible={setVisible} />

Set visible from outside:

  <button onClick={() => setVisible(!visible)}>Click</button>

Sample: https://codesandbox.io/s/competent-bassi-x3dqd?file=/src/App.js:267-325

You will need to "lift the state up" to a component that will pass the state and the state handlers to his children, or use some global state withredux or context .

Example:

<App> :

import Modal from "./modal";
import { useState } from "react";

const [visible, setVisible] = useState(false);

const showModal = () => {
  setVisible(true);
};

return (
  <> 
    <Button onClick={showModal}> Hide Modal </Button>
    <Modal visible={visible} />
  </>
);

<Modal> :

export default const Modal = ({ visible }) => {
  return (
    <Dialog visible={visible}>
      <h1>Hello Test</h1>
    </Dialog>
  );
};

Also, by only using the export keyword, you can import only single export from a module, therefore you can't use the default import syntax import Modal from "..." and you will be required to import as such - import { Modal } from '...'

I managed to solve usingEffect here, but not sure if this is perfect for my implementation. I am trying to update the state for already mounted component.

useEffect(() => {
    if (props.visible) {
      showModal();
    }
  }, [props.visible]);

And handled resetState with a callback prop

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