Yuk*_*hka 2 javascript reactjs material-ui styled-components
这是TextField使用withStylesMaterial-UI 本身的Material-UI样式:
export const STextField = withStyles({
root: {
background: 'white',
'& label.Mui-focused': {
color: 'white'
},
'& .MuiInput-underline:after': {
borderBottomColor: 'white'
},
'& .MuiOutlinedInput-root': {
'& fieldset': {
borderColor: 'white'
},
'&:hover fieldset': {
borderColor: 'white'
},
'&.Mui-focused fieldset': {
borderColor: 'white'
}
}
}
})(TextField);
Run Code Online (Sandbox Code Playgroud)
它完美无缺。
有什么办法可以使用相同的样式styled-components吗?
我试过这个:
export const STextField = styled(TextField)`
.MuiTextField-root {
background: 'white'
& label.Mui-focused: {
color: 'white'
},
& .MuiInput-underline:after: {
borderBottomColor: 'white'
},
& .MuiOutlinedInput-root: {
& fieldset: {
borderColor: 'white'
},
&:hover fieldset: {
borderColor: 'white'
},
&.Mui-focused fieldset: {
borderColor: 'white'
}
}
`;
Run Code Online (Sandbox Code Playgroud)
但它并没有制作相同的风格。
我可能会遗漏一些额外的语法,任何帮助表示赞赏!
下面是一个示例,显示了等效使用的正确语法styled-components。
它修复了以下语法问题:
您不需要用.MuiTextField-root {...}. 根级别是应用样式组件中的类名的级别。围绕样式.MuiTextField-root {...}将导致它不起作用,因为它将查找具有该类的 TextField 根元素的后代(但该类位于 TextField 根元素本身上)。
在向样式组件提供模板文字时,您需要使用 CSS 语法而不是 JS 对象语法。这意味着:
:在样式规则的括号之前whiteborder-color代替borderColor)import React from "react";
import TextField from "@material-ui/core/TextField";
import { withStyles } from "@material-ui/core/styles";
import styled from "styled-components";
const WithStylesTextField = withStyles({
root: {
background: "white",
"& label.Mui-focused": {
color: "white"
},
"& .MuiInput-underline:after": {
borderBottomColor: "white"
},
"& .MuiOutlinedInput-root": {
"& fieldset": {
borderColor: "white"
},
"&:hover fieldset": {
borderColor: "white"
},
"&.Mui-focused fieldset": {
borderColor: "white"
}
}
}
})(TextField);
const StyledTextField = styled(TextField)`
background: white;
& label.Mui-focused {
color: white;
}
& .MuiInput-underline:after {
border-bottom-color: white;
}
& .MuiOutlinedInput-root {
& fieldset {
border-color: white;
}
&:hover fieldset {
border-color: white;
}
&.Mui-focused fieldset {
border-color: white;
}
}
`;
export default function App() {
return (
<div>
<WithStylesTextField variant="standard" label="standard withStyles" />
<WithStylesTextField variant="outlined" label="outlined withStyles" />
<br />
<StyledTextField variant="standard" label="standard styled-comp" />
<StyledTextField variant="outlined" label="outlined styled-comp" />
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
667 次 |
| 最近记录: |