有没有一种方法可以在 React 应用程序中使用样式化组件,而无需重命名所有现有组件?
Is there a way to use styled-components in a React app, without renaming all existing components?
我想重构现有的 React 应用程序并添加 styled-components
。
问题是我看到这个工作的唯一方法是重命名所有现有的功能组件,创建新样式的组件,并用旧名称命名它们,这样当我使用它们构建应用程序时,它看起来是一样的.
我将此组件从 Button
重命名为 DefaultButton
:
class DefaultButton extends React.Component {
render() {
return <button className={this.props.className}>
{this.props.text}
</button>;
}
}
然后用旧名称创建样式组件:
let Button = styled(DefaultButton)`
color: ${props => props.theme.buttonStyles.color};
background-color: ${props => props.theme.buttonStyles.backgroundColor};
`;
Button.defaultProps = {
theme: {
buttonStyles: {
color: '#000',
backgroundColor: '#ccc'
}
}
};
export default Button;
现在我可以像以前一样使用它了:
<ThemeProvider theme={mytheme}>
<div className="App">
<Button text="Give me an answer here"></Button>
</div>
</ThemeProvider>
有没有办法添加新样式而不重命名所有现有组件?
欢迎任何 improvement/advice 以上代码。
谢谢!
不需要重命名组件,直接这样写就可以了
class Button extends React.Component {
render() {
return <button className={this.props.className}>
{this.props.text}
</button>;
}
}
Button = styled(Button)`
color: ${props => props.theme.buttonStyles.color};
background-color: ${props => props.theme.buttonStyles.backgroundColor};
`;
Button.defaultProps = {
theme: {
buttonStyles: {
color: '#000',
backgroundColor: '#ccc'
}
}
};
export default Button;
我想重构现有的 React 应用程序并添加 styled-components
。
问题是我看到这个工作的唯一方法是重命名所有现有的功能组件,创建新样式的组件,并用旧名称命名它们,这样当我使用它们构建应用程序时,它看起来是一样的.
我将此组件从 Button
重命名为 DefaultButton
:
class DefaultButton extends React.Component {
render() {
return <button className={this.props.className}>
{this.props.text}
</button>;
}
}
然后用旧名称创建样式组件:
let Button = styled(DefaultButton)`
color: ${props => props.theme.buttonStyles.color};
background-color: ${props => props.theme.buttonStyles.backgroundColor};
`;
Button.defaultProps = {
theme: {
buttonStyles: {
color: '#000',
backgroundColor: '#ccc'
}
}
};
export default Button;
现在我可以像以前一样使用它了:
<ThemeProvider theme={mytheme}>
<div className="App">
<Button text="Give me an answer here"></Button>
</div>
</ThemeProvider>
有没有办法添加新样式而不重命名所有现有组件? 欢迎任何 improvement/advice 以上代码。
谢谢!
不需要重命名组件,直接这样写就可以了
class Button extends React.Component {
render() {
return <button className={this.props.className}>
{this.props.text}
</button>;
}
}
Button = styled(Button)`
color: ${props => props.theme.buttonStyles.color};
background-color: ${props => props.theme.buttonStyles.backgroundColor};
`;
Button.defaultProps = {
theme: {
buttonStyles: {
color: '#000',
backgroundColor: '#ccc'
}
}
};
export default Button;