koo*_*ftr 3 reactjs material-ui styled-components
我需要制作 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}/>
};
Run Code Online (Sandbox Code Playgroud)
我需要将样式(不是类)传递给 Select 的弹出框部分,以在弹出框和输入之间留出边距。我尝试了一切并找到了向他们传递课程的唯一方法。但由于项目限制,我无法使用全局类或模块类,只能在js中传递。有任何想法吗?

如果您使用disablePortal: truemenu 属性,它将导致Popover成为 DOM 中 Select 根元素的后代。这允许您像下面这样定位它:
const Select = styled(MuiSelect)`
.MuiPopover-paper {
margin-top: 3px;
}
`;
Run Code Online (Sandbox Code Playgroud)
这是一个完整的工作示例:
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>
);
}
Run Code Online (Sandbox Code Playgroud)