使用 styled-components
的新手总数.我想知道它的用途是什么?样式化后我应该如何实现组件生命周期方法?为简单起见,我删除了所有其他样式。
import styled from 'styled-components';
const Button = styled.button`
background-color: 'green'
`
export default Button;
我想知道如何进一步处理
Button
零件?传统上我们可以声明一个基于类的组件并实现一些生命周期方法,但现在有了这个
styled-components
,我不确定如何将它们组合在一起,因为它们确实是单个 Button
零件?更新:
Button.js
的完整源代码.通过使用以下代码,所有样式都将消失,我无法理解问题import React from 'react';
import styled from 'styled-components';
// import Button from 'react-bootstrap/Button';
import color from '../config/color';
const Button = ({ children, onPress }) => (
<button type="button" onPress={onPress}>{children}</button>
);
const StyledButton = styled(Button)`
width: 12rem;
height: 54px;
font-size: 1rem;
background-color: ${(props) => {
if (props.inverted) return 'white';
if (props.disabled) return color.disabled;
return (props.color || color.primary);
}};
color: ${(props) => {
if (props.disabled) return color.disabledText;
if (props.inverted) return (props.color || color.primary);
return 'white';
}};
border:${(props) => (props.inverted ? `2px solid ${props.color || color.primary}` : 'none')};
border-radius: 60px;
&:hover {
filter: ${(props) => (props.inverted || props.disabled ? 'none' : 'brightness(95%)')}
}
`;
export default StyledButton;
最佳答案
为了设置自定义 React 组件的样式,您可以将自定义组件名称作为参数传递给 styled
.根据文档:
The styled method works perfectly on all of your own or any third-party component, as long as they attach the passed className prop to a DOM element.
import React from 'react';
import styled from 'styled-components';
// import Button from 'react-bootstrap/Button';
import color from '../config/color';
const Button = ({ children, className onPress }) => (
<button type="button" className={className} onPress={onPress}>{children}</button>
);
const StyledButton = styled(Button)`
width: 12rem;
height: 54px;
font-size: 1rem;
background-color: ${(props) => {
if (props.inverted) return 'white';
if (props.disabled) return color.disabled;
return (props.color || color.primary);
}};
color: ${(props) => {
if (props.disabled) return color.disabledText;
if (props.inverted) return (props.color || color.primary);
return 'white';
}};
border:${(props) => (props.inverted ? `2px solid ${props.color || color.primary}` : 'none')};
border-radius: 60px;
&:hover {
filter: ${(props) => (props.inverted || props.disabled ? 'none' : 'brightness(95%)')}
}
`;
export default StyledButton;
阅读
styled-component documentation
有关样式任何组件的更多详细信息
关于javascript - 如何在 react 组件中使用样式组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61748204/