我正在使用React和MaterialUI来构建一个系统,该系统将在另一个(而不是基于反应的)网站中显示小部件。我想让小部件响应,但它们需要响应自己的容器宽度,而不是窗口宽度,因为我不知道小部件将占用多少页面。
我已经考虑过的选择:
在我看来,这些都是相当丑陋的解决方案。有什么优雅的方法来做我想做的事吗?
发布于 2020-09-24 06:52:20
您可以侦听组件大小的更改,而不是断点。您可以使用反应-使用钩子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
包含在具有值200px
的容器组件MyContainer
中,当您调整浏览器视图的大小时,可以看到MyComponent
的border
颜色基于组件本身的大小(如果组件的宽度小于150px
,yellow
则为400px
,则为green
),否则它的green
就不是根据窗口的大小而定。
发布于 2019-03-08 01:43:41
为了使各种@material-ui/core
元素只占用放置它们的容器所占用的空间,我将使用Grid
组件。
我使用了以下方法:
<Grid container spacing={24}>
<Grid item>
Your content here
</Grid>
</Grid>
如果进一步希望网格项响应屏幕大小等内容,可以这样做:
const grid = {
xs: 24,
sm: 24,
md: 24,
lg: 12,
xl: 12,
};
和
<Grid item {...grid}>
https://stackoverflow.com/questions/55059681
复制相似问题