Перейти к контенту

Box

Box компонент используется как обертка компонента для большинства используемых CSS свойств.

The Box component packages all the style functions that are exposed in @material-ui/system.

Пример

The palette style function.

The sx prop

All system properties are available via the sx prop. In addition, the sx prop allows you to specify any other CSS rules you may need. Вот пример того, как вы можете использовать его:

import * as React from 'react';
import { Box, ThemeProvider } from '@material-ui/system';

export default function BoxSx() {
  return (
    <ThemeProvider
      theme={{
        palette: {
          primary: {
            main: '#00cc44',
            dark: '#00802b',
          },
        },
      }}
    >
      <Box
        sx={{
          width: 300,
          height: 300,
          bgcolor: 'primary.dark',
          '&:hover': {
            backgroundColor: 'primary.main',
            opacity: [0.9, 0.8, 0.7],
          },
        }}
      />
    </ThemeProvider>
  );
}

Переопределение Material-UI компонентов

Box компонент оборачивает ваш компонент. Он создает новый DOM элемент: <div> по умолчанию, который можно изменить свойством component. Например если вы хотите использовать<span> взамен:

import * as React from 'react';
import { Box } from '@material-ui/system';
import Button from '@material-ui/core/Button';

export default function BoxComponent() {
  return (
    <Box component="span" sx={{ p: 2, border: '1px dashed grey' }}>
      <Button>Save</Button>
    </Box>
  );
}

Это работает превосходно когда изменения могут быть изолированы в новый DOM элемент. Для сущности, вы можете изменить margin(внешний отступ) таким образом.

Тем не менее, иногда вам нужно ориентироваться на базовый элемент DOM. As an example, you may want to change the border of the Button. Этот компонент определяет свои собственные стили. Наследование CSS не помогает. To workaround the problem, you can use the sx prop directly on the child if it is a Material-UI component.

-<Box sx={{ border: '1px dashed grey' }}>
-  <Button>Save</Button>
-</Box>
+<Button sx={{ border: '1px dashed grey' }}>Save</Button>

For non-Material-UI components, use the component prop.

-<Box sx={{ border: '1px dashed grey' }}>
-  <button>Save</button>
-</Box>
+<Box component="button" sx={{ border: '1px dashed grey' }}>Save</Box>

API

import Box from '@material-ui/core/Box';
Имя Тип По-умолчанию Описание
children node
Box render function or node.
component union: string |
 func |
 object
'div' The component used for the root node. Either a string to use a DOM element or a component.
sx object {} Принимает все системные свойства, а также все допустимые CSS-свойства.

System props

As a CSS utility component, the Box also supports all system properties. You can use them as prop directly on the component. For instance, a margin-top:

<Box mt={2}>