reactjs - 如何样式化material-ui select
问题描述
我需要制作一个风格化版本的 material-ui 选择组件。我现在拥有的是:
import { Select } from '@material-ui/core';
import type { SelectProps } from '@material-ui/core';
import styled from 'styled-components';
const menuProps = {
getContentAnchorEl: null,
anchorOrigin: {
vertical: "bottom",
horizontal: "left",
},
PopoverClasses: {
// pass only classnames
}
}
const StyledSelect = styled(Select)<SelectProps>`
... some styles
`;
const Select: React.FC<SelectProps> = (props) => {
return <StyledSelect MenuProps={menuProps} {...props}/>
};
我需要将样式(NOT CLASSES)传递给 Select 的弹出框部分,以在弹出框和输入之间留出余量。我尝试了一切,并找到了将课程传给他们的唯一方法。但是由于项目限制,我不能使用全局类或模块类,只能在js中传递它们。有任何想法吗?
解决方案
如果你使用disablePortal: true
menu 属性,它会导致Popover
DOM 成为 Select 的根元素的后代。这使您可以像下面这样定位它:
const Select = styled(MuiSelect)`
.MuiPopover-paper {
margin-top: 3px;
}
`;
这是一个完整的工作示例:
import React from "react";
import InputLabel from "@material-ui/core/InputLabel";
import MenuItem from "@material-ui/core/MenuItem";
import MuiFormControl from "@material-ui/core/FormControl";
import MuiSelect from "@material-ui/core/Select";
import styled from "styled-components";
import { StylesProvider } from "@material-ui/core/styles";
const FormControl = styled(MuiFormControl)`
margin: 8px;
min-width: 120px;
`;
const Select = styled(MuiSelect)`
.MuiPopover-paper {
margin-top: 3px;
}
`;
export default function SimpleSelect() {
const [age, setAge] = React.useState("");
const handleChange = event => {
setAge(event.target.value);
};
const menuProps = {
getContentAnchorEl: null,
anchorOrigin: {
vertical: "bottom",
horizontal: "left"
},
disablePortal: true
};
return (
<StylesProvider injectFirst>
<div>
<FormControl>
<InputLabel id="demo-simple-select-label">Age</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={age}
onChange={handleChange}
MenuProps={menuProps}
>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</FormControl>
</div>
</StylesProvider>
);
}
推荐阅读
- python - Apache2 上的第二个 Flask 应用程序出现问题
- amazon-redshift - 从 Redshift 中的 sysdate 减去 5 小时
- fortran - 有效性 - 从未格式化的二进制文件读取时检查逻辑值
- vb.net - 未为类型“DBNull”和类型“DBNull”定义运算符“=”
- javascript - 为什么函数的原型必须是它的孩子?
- reactjs - 是否可以将 React.hook 传递给函数?
- php - Google API 服务器到服务器身份验证 PHP
- arrays - 如何根据多个值对数据数组进行分组?
- c# - 实体框架未将新创建的对象 ID 分配给子对象
- mysql - 从 mySQL 显示多个 Blob 文件