chengaofeng
发布于 2024-09-07 / 13 阅读
0
0

React实践过程中的一些技巧

  1. 我们在封装React组件时,通常是将小组件移出去,还有一个方式就是通过children传递,将外层组件移出去,而在最上层维护最里面的组件,在某些时候特别有用。

import React from 'react';
import { Button, Modal } from 'antd';

interface ContainerProps {
  children?: React.ReactNode;
}

const Container = ({ children }: ContainerProps) => {
  const [open, setOpen] = React.useState(false);

  return (
    <>
      <Button
        type="link"
        key="enable"
        size="small"
        css={{ color: 'green' }}
        onClick={() => setOpen(true)}
      >
        按钮
      </Button>
      <Modal
        title="test"
        open={open}
        footer={false}
        onCancel={() => setOpen(false)}
      >
        {children}
      </Modal>
    </>
  );
};

export interface MaintainButtonProps {}

const MaintainButton: React.FC<
  MaintainButtonProps
> = ({}: MaintainButtonProps) => {
  return <Container>主要内容在这里写</Container>;
};

export default React.memo(MaintainButton);


评论