使用Styled-components react写一个demo
时间: 2024-03-14 19:43:20 浏览: 17
好的,以下是一个简单的Styled-components React Demo:
```jsx
import React from 'react';
import styled from 'styled-components';
const Button = styled.button`
background-color: ${props => props.primary ? '#007bff' : '#6c757d'};
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
margin-right: 10px;
&:hover {
background-color: ${props => props.primary ? '#0062cc' : '#5a6268'};
}
`;
const Container = styled.div`
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
`;
function App() {
return (
<Container>
<Button>Default</Button>
<Button primary>Primary</Button>
</Container>
);
}
export default App;
```
在上面的代码中,我们使用了 `styled-components` 库来创建一个名为 `Button` 的组件,并使用模板字符串语法定义了一些 CSS 样式。然后,我们定义了一个名为 `Container` 的组件,该组件将其子组件居中显示。
在 `App` 组件中,我们使用 `Button` 组件创建了两个按钮,一个是默认风格,另一个是主题风格。这是通过为 `primary` 属性传递 `true` 来实现的。
当我们将应用程序运行时,我们将看到两个按钮,一个蓝色的默认按钮,一个深灰色的主题按钮,并且当我们将鼠标悬停在按钮上时,它们的背景颜色会发生变化。
希望这个简单的 demo 对你有帮助!