As a brick moving engineer, I have been using ANTD (Ant Design), because its rich component library to management background development brought a lot of convenience, there are also a lot of implementation schemes worth learning, this article to Popconfirm implementation to do an introduction.

Let’s take a look at how it works. Here’s an official example:

import { Popconfirm, message } from 'antd';

function confirm(e) {
  console.log(e);
  message.success('Click on Yes');
}

function cancel(e) {
  console.log(e);
  message.error('Click on No');
}

ReactDOM.render(
  <Popconfirm
    title="Are you sure to delete this task?"
    onConfirm={confirm}
    onCancel={cancel}
    okText="Yes"
    cancelText="No"
  >
    <a href="#">Delete</a>
  </Popconfirm>,
  mountNode,
);
Copy the code

The page is displayed as follows

In the above code example, we just wrapped a Popconfirm component on the outside of a label. However, we did not define the click event of A. All the configuration was directly placed on Popconfirm, so the above functions could be realized.

We can also see that the code intrusion is very small in the very simple way of use. If we do not need Popconfirm on that day, we can directly delete the Popconfirm component and move the operation on onConfirm to the onClick of A.

However, there are some questions when using it. There is no event bound to A, but why will the confirmation box be triggered when clicking?

The react. cloneElement method is used to copy elements and modify their properties.

Source location 1: Components/popConfirm

Components /_util/reactNode.ts (react.cloneElement)

React. CloneElement I read the official documentation for React. The description is simple and clear

With this in mind, we can implement some pluggable components, such as the following component in ANTD

  • tooltip
  • popover
  • dropdown
  • .

If you dig deeper into ANTD, you’ll notice that the input under form. Item is not bound to value or onChange, but how the Form gets data is also implemented through react. cloneElement.