React:如何将函数作为props从功能父组件传递给子组件

IT技术 reactjs react-props
2021-05-01 17:20:44

父组件:

const initialValue_modalProps = [
    { show: false, response: "" }
  ];
const [modalProps, setModalProps] = useState(initialValue_modalProps)
const passedFunction = () => {
    setModalProps(modalProps => initialValue_modalProps);
  }
..
..
 <div>
        <Modal show={modalProps.show}
          response={modalProps.response}
          passedFunction={passedFunction}></Modal>
 </div>

子组件:

export default function ModalComp(props) {
    const [modalOpen, setmodalOpen] = useState(true);
    console.log('modalOpen', modalOpen);
    if (props.show === false || modalOpen === false) {
        return null;
    }
    return (<Modal isOpen={props.show}>
        <ModalHeader>Deployment Status</ModalHeader>
        <ModalBody>{props.response}</ModalBody>
        <ModalFooter>
            <Button onClick={() => {
                setmodalOpen(modalOpen => false);
                props.passedFunction();
            }}>Close</Button>
        </ModalFooter>
    </Modal>)

}

这里我想把Function函数从Parent传递给child,这样子组件就可以执行它来重置parent中的状态

3个回答

您可以将此作为现场示例演示https://codesandbox.io/s/musing-mendeleev-6fvyx的参考

function App() {
  const [status, setState] = React.useState(false);
  const [text, setText] = React.useState("");
  const handleClick = () => {
    this.setState(prev => ({ status: !prev.status }));
  };
  const handleChange = e => {
    this.setState({ text: e.target.value });
  };

  return (
    <>
      <button onClick={handleClick}>Open photo entry dialog</button>
      <ChildComponent
        isOpen={status}
        text={text}
        handleChange={handleChange}
        handleClick={handleClick}
      />
    </>
  );
}

const ChildComponent = ({ isOpen, text, handleChange, handleClick }) => {
  return (
    <>
      {isOpen && (
        <Model
          status={isOpen}
          handleClick={handleClick}
          text={text}
          handleChange={handleChange}
        />
      )}
    </>
  );
};

您需要删除 后面的括号passedFunction,否则您将首先执行该函数,然后将结果传递给子项。通过passedFunction={passedFunction}.

const ParentComponent = () => {

  const initialModalProps = { ... };
  const [modalProps, setModalProps] = useState(initialModalProps);

  const passedFunction = () => {
    setModalProps(initialModalProps);
  }

  return (
    <div>
      <Modal
        show={modalProps.show}
        response={modalProps.response}
        passedFunction={passedFunction} />
    </div>
  );

};

将子组件更改为此。及其工作

export default function ModalComp(props) {
    //const [modalOpen, setmodalOpen] = useState(true);
    if (props.show === false) {
        return null;
    }
    return (<Modal isOpen={props.show}>
        <ModalHeader>Deployment Status</ModalHeader>
        <ModalBody>{props.response}</ModalBody>
        <ModalFooter>
            <Button onClick={props.passedFunction}>Close</Button>
        </ModalFooter>
    </Modal>)