1 javascript ecmascript-6 reactjs styled-components
我有以下内容Button.js
:
import styled from 'styled-components';
const Button = styled.button`
background: black;
border: none;
color: white;
outline: none;
${props => props.add && css`
background: palevioletred;
color: white;
`};
${props => props.delete && css`
background: palevioletred;
color: white;
`};
`;
export default Button;
Run Code Online (Sandbox Code Playgroud)
但是当我运行它时,在编译过程中出现以下错误:
./src/components/Button.js第10行:未定义'css'no-undef第15行:未定义'css'no-undef
然后,我使用如下按钮:
<Button delete>Delete</Button>
<Button add>Add</Button>
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么?
小智 6
您是否尝试导入CSS?
import styled, { css } from 'styled-components'
Run Code Online (Sandbox Code Playgroud)
所以你的代码应该是
import styled, { css } from 'styled-components';
const Button = styled.button`
background: black;
border: none;
color: white;
outline: none;
${props => props.add && css`
background: palevioletred;
color: white;
`};
${props => props.delete && css`
background: palevioletred;
color: white;
`};
`;
export default Button;
Run Code Online (Sandbox Code Playgroud)
小智 0
最后通过以下方式“弄清楚”:
import styled from 'styled-components';
const Button = styled.button`
background: black;
border: none;
color: white;
outline: none;
${(props) => {
if (props.add) {
return 'background: green;'
} else if (props.delete) {
return 'background: red;'
} else {
return 'background: black;'
}
}}
`;
export default Button;
Run Code Online (Sandbox Code Playgroud)
这是有效的......即使在我上面的问题中我完全遵循了文档。
归档时间: |
|
查看次数: |
5007 次 |
最近记录: |