探索Chakra UI React组件库

Despite my love for Tailwind CSS over other frameworks, I have always been disappointed by the lack of components like what we get with more fully fledged-out frameworks like Bootstrap and Materialize. I recently discovered the perfect solution to this problem: Chakra UI.

尽管我对Tailwind CSS的喜爱超过了其他框架,但我始终对缺少像Bootstrap和Materialize这样更完善的框架所提供的组件感到失望。 我最近发现了解决此问题的完美解决方案: Chakra UI

Chakra UI follows the same minimalistic and modular approach as Tailwind CSS, so you don’t need to waste anymore time undoing and overriding the default configurations.

Chakra UI遵循与Tailwind CSS相同的简约和模块化方法,因此您不再需要浪费时间来撤消和覆盖默认配置。

In this article, we’re going to get started exploring the best of what this framework can do for us and why it’s unique.

在本文中,我们将开始探索该框架可以为我们做的最好的事情,以及它为什么独特的原因。

安装 (Installation)

Installation is a bit awkward since there are a few peer dependencies which, I think, should just come with it by default, but that’s how it is for some reason ¯\_(ツ)_/¯.

安装有点尴尬,因为我认为默认情况下应该附带一些同级依赖,但是出于某些原因,这就是安装方式。

We just need Chakra UI itself and a few things from Emotion, since Chakra UI is dependent on 👩‍🎤 emotion, the CSS-in-JS library.

我们只需要Chakra UI本身和Emotion的一些功能,因为Chakra UI依赖于CSS-in-JS👩‍🎤motion

We’ll make use of npx and Create React App to initialize our React app:

我们将使用npx和Create React App来初始化我们的React应用程序:

$ npx create-react-app chakra-app
$ npm install @chakra-ui/core @emotion/core @emotion/styled emotion-theming

建立 (Setup)

Before we can do anything we need to wrap our whole app in a ThemeProvider, which establishes all of the default styles for our components.

在执行任何操作之前,我们需要将整个应用程序包装在ThemeProvider ,该主题将为组件建立所有默认样式。

index.js
index.js
import { ThemeProvider } from "@chakra-ui/core";

const ThemedApp = () => <ThemeProvider> <App /> </ThemeProvider>;

ReactDOM.render(<ThemedApp />, document.getElementById('root'));

布局 (Layout)

Besides our normal UI components like sliders and dropdowns, Chakra UI gives us a few “meta components” (not the official term), for easily adding a responsive layout of multiple components. With all of them you can pass-in the properties you’d expect, like bg or justifyContent in CSS as props.

除了我们的普通UI组件(如滑块和下拉菜单)之外,Chakra UI还为我们提供了一些“元组件”(不是官方术语),以便轻松添加多个组件的响应式布局。 通过所有这些,您可以传入期望的属性,例如CSS中的bgjustifyContent作为props。

  • Stack - Groups a set on components with equal spacing, is vertical by default but can be overridden with isInline.

    Stack -对一组具有相等间距的组件进行分组,默认情况下为垂直,但可以使用isInline覆盖。

  • Flex - Wraps everything in a Flexbox container.

    Flex所有内容包装在Flexbox容器中

  • Grid - Wraps everything in a CSS Grid container.

    Grid -将所有内容包装在CSS网格容器中

  • Box - Just a div for receiving style props.

    Box只是一个用于接收样式道具的div。

App.js
App.js
import { Stack, Flex, Box, Grid } from "@chakra-ui/core";

const App = () => {
  const flexSettings = {
    flex: "1",
    minW: "300px",
    textAlign: "center",
    color: "white",
    mx: "6",
    mb: "6"
  };

  const gridSettings = {
    w: "100%",
    textAlign: "center",
    color: "white",
  };

  return (
    <div>
      <Flex w="100%" justify="space-between" flexWrap="wrap">
        <Box {...flexSettings} bg={"red.500"}>I'm a box</Box>
        <Box {...flexSettings} bg={"blue.500"}>I'm a box</Box>
        <Box {...flexSettings} bg={"green.500"}>I'm a box</Box>
        <Box {...flexSettings} bg={"purple.500"}>I'm a box</Box>
      </Flex>

      <Grid w="100%" templateColumns="repeat(auto-fit, minmax(300px, 1fr))" gap={6}>
        <Box {...gridSettings} bg={"red.500"}>I'm a box</Box>
        <Box {...gridSettings} bg={"blue.500"}>I'm a box</Box>
        <Box {...gridSettings} bg={"green.500"}>I'm a box</Box>
        <Box {...gridSettings} bg={"purple.500"}>I'm a box</Box>
      </Grid>
    </div>
  );
};

造型 (Styling)

Since Chakra UI is based on Emotion for styling, is allows for using CSS-in-JS and adds its own shorthand for common properties in the same style as Tailwind CSS, that’s why we were able to use w and templateColumns instead of width and gridTemplateColumns.

由于Chakra UI基于Emotion进行样式设置,因此允许使用CSS-in-JS并以与Tailwind CSS相同的样式添加其自己的通用属性简写,这就是为什么我们能够使用wtemplateColumns而不是widthgridTemplateColumns

If you’re unfamiliar with this approach to styling, it’s a way of writing your CSS so you get all the JavaScript goodies that even Sass doesn’t come with, like connecting a style to the state of a component.

如果您不熟悉这种样式化方法,那么这是一种编写CSS的方式,因此您可以获得Sass所没有的所有JavaScript好东西,例如将样式连接到组件的状态。

In this example, we’re basing the styles of a box off the component’s state and using a little UI to manipulate it.

在此示例中,我们将框的样式置于组件状态的基础上,并使用一些UI对其进行操作。

App.js
App.js
const BoxController = () => {
  let [boxHeight, editHeight] = useState(20);
  let [boxColor, editColor] = useState('red');
  let [colorIntensity, editIntensity] = useState(500);

  const boxSettings = {
    flex: "1",
    textAlign: "center",
    color: "white",
    h: `${boxHeight}px`,
    bg: `${boxColor}.${colorIntensity}`
  };

  return (
    <div>
      <Box {...boxSettings}>I'm a Box</Box>
      <Flex justifyContent="space-around">
        <Stack>
          <Heading size="md">Size</Heading>
          <Button variantColor="red" onClick={() => editHeight(boxHeight -= 10)} border="none">Shrink</Button>
          <Button variantColor="green" onClick={() => editHeight(boxHeight += 10)} border="none">Grow</Button>
        </Stack>

        <Stack>
          <Heading size="md">Color</Heading>

          <Flex w="200px" justifyContent="space-between">

            <Stack>
              <Button variantColor="green" onClick={() => editColor('green')} border="none">Green</Button>
              <Button variantColor="blue" onClick={() => editColor('blue')} border="none">Blue</Button>
              <Button variantColor="red" onClick={() => editColor('red')} border="none">Red</Button>
            </Stack>

            <Stack>
              <Button variantColor="gray" variant="outline" onClick={() => editIntensity(colorIntensity -= 100)} border="none">Lighter</Button>
              <Button variantColor="gray" variant="outline" onClick={() => editIntensity(colorIntensity += 100)} border="none">Darker</Button>
            </Stack>

          </Flex>
        </Stack>
      </Flex>
    </div>
  );
};

组件 (Components)

We obviously can’t go over every component, so let’s just focus on a few that are unique to Chakra UI.

显然我们无法遍历每个组件,因此让我们仅关注Chakra UI特有的一些组件。

抽屉 (Drawer)

The drawer component is a clean little slide out mechanism that would be perfect for any side navbar. Note that it uses Chakra’s custom useDisclosure hook that gives us isOpen, onOpen, and onClose for controlling the state of our drawer and any similar components, like a modal.

抽屉组件是一个干净的小滑出装置,非常适合任何侧面导航栏。 请注意,它使用Chakra的自定义useDisclosure钩子,该钩子为我们提供isOpenonOpenonClose来控制抽屉和任何类似组件(如模式)的状态。

App.js
App.js
import {
  Drawer,
  DrawerBody,
  DrawerFooter,
  DrawerHeader,
  DrawerOverlay,
  DrawerContent,
  DrawerCloseButton,
  Input,
  Button,
  useDisclosure,
  Stack,
  Textarea
} from "@chakra-ui/core"

const SignUpForm = () =>  {
  const { isOpen, onOpen, onClose } = useDisclosure();
  const btnRef = useRef();

  return (
    <div>
      <Button ref={btnRef} variantColor="teal" border="none" onClick={onOpen}>
        Sign Up
      </Button>
      <Drawer
        isOpen={isOpen} placement="bottom"
        onClose={onClose} finalFocusRef={btnRef}
      >
        <DrawerOverlay />
        <DrawerContent>

          <DrawerCloseButton border="none" />
          <DrawerHeader>Sign up Now</DrawerHeader>

          {/* Form */}
          <DrawerBody >
            <Stack height="30vh">
              <Input w="98%" placeholder="Name" />
              <Input w="98%" placeholder="Email" />
              <Textarea w="98%" h="100%" placeholder="Message" />
            </Stack>
          </DrawerBody>

          <DrawerFooter>
            <Button variantColor="red" border="none" mr={3} onClick={onClose}>
              Cancel
            </Button>
            <Button variantColor="blue" border="none">Save</Button>
          </DrawerFooter>

        </DrawerContent>
      </Drawer>
    </div>
  );
}

装载机 (Loaders)

Chakra UI offers us a nice array of animated loaders that are insanely easy to customize. In this example I’ve added a loop to see our loaders in action, but they don’t need to be based on anything external, they can also be completely static.

Chakra UI为我们提供了一系列很好的动画加载器,它们易于定制。 在此示例中,我添加了一个循环以查看加载程序的运行情况,但是它们不需要基于任何外部程序,它们也可以是完全静态的。

App.js
App.js
import {
  Stack,
  CircularProgress,
  CircularProgressLabel,
  Progress,
  Spinner
} from "@chakra-ui/core"

const Spinners = () => {
  let [progress, update] = useState(0)

  const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1) + min)

  useEffect(() => setInterval(() => {
    // Reset to 0 when reaches 100
    update(progress < 100 ? progress += randomNum(0, 4) : 0)
  }, 500), [])

  return (
    <div>
      <Stack>
        <CircularProgress color="green" isIndeterminate>
          <CircularProgressLabel>{progress}%</CircularProgressLabel>
        </CircularProgress>
        <CircularProgress value={progress} size="100px" thickness={0.1} color="purple" />
        <Progress value={progress} w="90%" />
        <Progress value={progress + 10} w="90%" hasStripe isAnimated />
        <Spinner
          thickness="3px"
          speed="1s"
          emptyColor="gray.200"
          color="blue.500"
          size="2xl"
        />
      </Stack>
    </div>
  );
}

主题 (Themes)

Something I have yet to see from any other framework is the ability to set themes over the entirety of your app. Whether it be a dark theme or a winter theme we can easily customize the style across our whole site/app in one place.

我还没有从任何其他框架中看到的是能够在整个应用程序中设置主题的功能。 无论是深色主题还是冬季主题,我们都可以在一个地方轻松地在整个网站/应用中自定义样式。

In this example I’ve added a few boxes whose designs and text will be based on the holiday season. I personally love when sites give you the option to pick which design you like best, like Alligator.io does. 😉

在此示例中,我添加了一些框,其设计和文本将基于假日季节。 我个人喜欢网站为您提供选择最喜欢的设计(例如Alligator.io)的选项。 😉

index.js
index.js
import { useTheme, ThemeProvider } from "@chakra-ui/core"


const ThemedApp = () => {
  const theme = useTheme()
  const customTheme = {
    ...theme,
    colors: { ...theme.colors },
    holidays: {
        text: {
          none: "Welcome to the site!",
          stPatricksDay: "Happy St.Patty's Day!",
          valentinesDay: "Happy Valentines Day!",
          halloween: "Good luck trick-or-treating!",
          christmas: "Merry Christmas!"
        },
        colors: {
            none: {
              "one": "#808080",
              "two": "#808080",
              "three": "#808080"
            },
            stPatricksDay: {
              "one": "#224D17",
              "two": "#60A830",
              "three": "#099441"
            },
            valentinesDay: {
              "one": "#b11d4d",
              "two": "#fd6fa0",
              "three": "#e986a3"
            },
            halloween: {
              "one": "#810806",
              "two": "#BF200E",
              "three": "#FA4113"
            },
            christmas: {
              "one": "#44b09e",
              "two": "#e0d2c7",
              "three": "#e01c34"
            },
        }
      }
  };
  return (
    <div>
      <ThemeProvider theme={customTheme}><App /></ThemeProvider>
    </div>
  )
}
App.js
App.js
import {
  Flex,
  Button,
  useTheme,
  Box
} from "@chakra-ui/core"

const HolidayPicker = () => {
  const [holiday, updateHoliday] = useState("none")
  const theme = useTheme()

  const holidayText = theme.holidays.text[holiday]
  const holidayColor = theme.holidays.colors[holiday]

  const btnStyles = {
    border: 'none',
    h: '25px',
    borderRadius: '20px',
    color: 'white',
    fontWeight: 'bold',
    cursor: 'pointer'
  }
  return (
    <div>
      <Flex justifyContent="space-around">
        <Box bg={holidayColor.one} w="100%" h="400px" color="white">{holidayText}</Box>
        <Box bg={holidayColor.two} w="100%" h="400px" color="white">{holidayText}</Box>
        <Box bg={holidayColor.three} w="100%" h="400px" color="white">{holidayText}</Box>
      </Flex>

      <Flex justifyContent="space-around" mt="20px">
        <Button bg={theme.holidays.colors.none} {...btnStyles}
          onClick={() => updateHoliday('none')}>None</Button>
        <Button bg={theme.holidays.colors.stPatricksDay} {...btnStyles}
          onClick={() => updateHoliday('stPatricksDay')}
        >St.Patrick's Day</Button>
        <Button bg={theme.holidays.colors.valentinesDay} {...btnStyles}
          onClick={() => updateHoliday('valentinesDay')}
        >Valentine's Day</Button>
        <Button bg={theme.holidays.colors.halloween} {...btnStyles}
          onClick={() => updateHoliday('halloween')}
        >Halloween</Button>
        <Button bg={theme.holidays.colors.christmas} {...btnStyles}
          onClick={() => updateHoliday('christmas')}
        >Christmas</Button>
      </Flex>
    </div>
  );
}

总结思想 (Closing Thoughts)

Together with TailwindCSS, Chakra UI has easily become one of the essential tools in all of my projects. It’s constantly improving and even now there are a few pull requests like appBar and carousel components that’ll probably be added soon. I hope this was enough to help you decide if Chakra UI deserves to be in your React/UI arsenal.

Chakra UI与TailwindCSS一起已轻松成为我所有项目中必不可少的工具之一。 它一直在不断改进,即使现在有一些拉取请求(如appBar和转盘组件)也可能会很快添加。 我希望这足以帮助您确定Chakra UI是否值得出现在您的React / UI工具库中。

翻译自: https://www.digitalocean.com/community/tutorials/react-chakra-ui

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值