Вместо точек останова вы можете прослушивать изменения размера компонента. Вы можете использовать хук response-use useMeasure для достижения этой цели (он полагается на ResizeObserver, который поддерживается всеми основными браузерами), как в следующем примере:
/** @jsx jsx */
import { css, jsx } from '@emotion/core';
import { faAddressBook, faCoffee } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { useMeasure } from 'react-use';
const useMyComponentStyle = (params) => {
const { color } = params;
const [ref, { width }] = useMeasure();
const borderColor = width < 150 ? 'red' : width < 400 ? 'yellow' : 'green';
const icon = width < 250 ? faCoffee : faAddressBook;
const style = css`
color: ${color};
padding: 10px;
border: 1px solid ${borderColor};
`;
return {
ref,
style,
icon,
width,
};
};
export const MyComponent = (props) => {
const { ref, style, icon, width } = useMyComponentStyle(props);
return (
<div ref={ref} css={style}>
<FontAwesomeIcon icon={icon} />
{props.children} [[{parseInt('' + width)}px]]
</div>
);
};
const containerStyle = css`
padding: 100px 200px;
border: 1px solid blue;
`;
export const MyContainer = () => (
<div css={containerStyle}>
<MyComponent color='blue'></MyComponent>
</div>
);
ReactDOM.render(<MyContainer />, document.getElementById('root'));
В приведенном выше примере для стилей css используется эмоция, но стиль можно определить с помощью другой библиотеки, например jss или стилизованные компоненты или даже простой встроенный стиль реакции.
Компонент MyComponent
включен в компонент контейнера MyContainer
, который имеет левую и правую padding
со значением 200px
, и при изменении размера окна браузера вы можете видеть, что border
цвет MyComponent
основан на размере самого компонента strong> (red
, если ширина компонента меньше 150px
, yellow
, если она меньше 400px
, иначе green
), не в зависимости от размера окна.
person
Lucas Basquerotto
schedule
24.09.2020