简体   繁体   中英

Event handler not displaying component

on clicking <button> , a click handler is invoked, in which a react component <ConfirmationDialog> is returned. But <ConfirmationDialog> is not getting invoked and displaying. why?

// App.js

import ConfirmationDialog from "./ConfirmationDialog";

export default function App() {
  const handleClick = () => {
    console.log("handle click");
    return <ConfirmationDialog />; // called from click handler
  };
  return <button onClick={handleClick}>click</button>;
}

// ConfirmationDialog.js

import * as React from "react";

export default function ConfirmationDialog() { // child component
  console.log("confirmation dialog");
  return <p>Confirmation dialog component</p>;
}

Why is click handler handleClick not rendering <ConfirmationDialog> ?

CodeSandbox Demo

See the updated codesandbox

Because you are returning a component from a function that is called within an event handler. You need to use state to actively hide or show components in the way you want.

In this case we have a state that is initally set to false, this state determines whether to show the confirmation box or not, in the handle click function, we set the state to true which allows the confirmation box to become visible. If the state were to be set to false once again, then the confirmation box would become invisible.

import ConfirmationDialog from "./ConfirmationDialog";
import { useState } from "react";

export default function App() {
  const [confirm, setConfirm] = useState(false); //state that determines whether to show confirm box or not
  const handleClick = () => {
    console.log("handle click");
    setConfirm(true); // decide to show the confirmation box
  };
  return (
    <>
      <button onClick={handleClick}>click</button>
      {confirm && <ConfirmationDialog />} // condition for showing the confirmation dialog
    </>
  );
}

This isn't how you do this, you need to create a state boolean variable and render the component if this variable is true and hide it when it is false

import ConfirmationDialog from "./ConfirmationDialog";

export default function App() {
  const [isVisible, setIsVisible] = useState(false)
  const toggleVisibility = () => {
    setIsVisible(isVisibleCurrentValue =>!isVisibleCurrentValue)
  };
  return <>
  <button onClick={toggleVisibility}>click</button>
  {isVisible && <ConfirmationDialog />}
  </>;
}

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