我正在为我的应用程序使用 antd。我需要将默认主按钮的颜色从蓝色更改为灰色。似乎 antd 没有提供这样的选项。如何轻松更改按钮颜色?
Den*_*ash 15
正式的解决方案antd是style每个组件的 API 中提到的道具:
<Button type="primary" style={{ background: "red", borderColor: "yellow" }}>
Submit
</Button>;
Run Code Online (Sandbox Code Playgroud)
此外,当您想要覆盖应用程序中每个组件的样式时,您应该覆盖 CSS 类或前面提到的自定义主题。
// Should be used for overriding all buttons.
// Import the css on entry point.
.ant-btn-primary {
background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
另外,请注意,您可以设置按钮容器的样式并为其颜色设置目标(不影响整个应用程序样式):
.button-container {
.ant-btn-primary {
background-color: palevioletred;
}
}
Run Code Online (Sandbox Code Playgroud)
CSS-in-JS 的示例:
const ButtonContainer = styled.div`
.ant-btn-primary {
background-color: red;
}
`;
const App = () => {
return (
<ButtonContainer>
<Button type="primary">My Button</Button>
</ButtonContainer>
);
};
Run Code Online (Sandbox Code Playgroud)
我不熟悉 Ant Design,但是您可以在他们的文档(自定义主题)中看到您可以像这样编辑原色:
@primary-color: #1890ff; // primary color for all components
Run Code Online (Sandbox Code Playgroud)
如果您只想更改按钮的颜色,您可以创建一个新的变量:
@button-color: #757575; // a custom variable
Run Code Online (Sandbox Code Playgroud)
然后添加一条规则(这将覆盖源):
.ant-btn-primary {
background-color: @button-color;
}
Run Code Online (Sandbox Code Playgroud)
根据最新的文档,最佳实践是使用ConfigProvider:
<ConfigProvider
theme={{
token: {
colorPrimary: '#00b96b',
},
}}
>
<Button />
</ConfigProvider>
Run Code Online (Sandbox Code Playgroud)
参考: https: //ant.design/docs/react/customize-theme#customize-design-token