gpt4 book ai didi

javascript - 使用 Create React App 进行 React 样式化

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:58:24 24 4
gpt4 key购买 nike

我是 React 新手。

引自 Create React App :

Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a .Button CSS class in AcceptButton and RejectButton components, we recommend creating a Button component with its own .Button styles, that both AcceptButton and RejectButton can render (but not inherit).

Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition.

我不认为我完全理解它。为什么 sass 嵌套和混合对组合的用处不大?有什么例子吗?

这是否也意味着我不应该有全局样式,例如,输入字段?如果我的应用程序中的所有输入字段看起来都相同或相似,我应该为其创建一个组件,只是为了样式目的吗?

最佳答案

SASS 嵌套有助于确保您的样式不会泄漏到父类之外。对于组件组合,这是自动执行的,因为您将组件嵌套在组件中。

Mixins 是一种跨选择器重用样式的方法。通过组件组合,重用来自于 JSX 而不是 CSS 中的组合。

老办法

CSS

.button {
color: #fff;

&.button-accept {
background-color: green;
}

&.button-reject {
background-color: red;
}
}

JSX

function AcceptButton() {
return <button className="button button-accept">Accept</button>;
}

function RejectButton() {
return <button className="button button-reject">Reject</button>;
}

react 方式

const buttonStyles = { color: '#fff' };

function Button(props) {
return <button style={Object.assign({}, buttonStyles, props.style)}>
{props.children}
</button>;
}

const acceptStyles = { backgroundColor: 'green' };

function AcceptButton(props) {
return <Button style={acceptStyles}>Accept</Button>;
}

const rejectStyles = { backgroundColor: 'red' };

function RejectButton(props) {
return <Button style={rejectStyles}>Reject</Button>;
}

请注意,这使用了内联样式,这在您重复呈现相同元素并且 DOM 中的每个元素都存在样式的现实情况下可能并不理想。要解决这个问题,请查看一些 CSS-in-JS 解决方案,例如 JSS .

Does that also mean I shouldn't have global styles, for example, for an input field? If in my app all the input fields look the same or similar, I should create a component for it, just for the styling purpose?

这取决于您是否使用任何 UI 框架。如果您要从头开始推出自己的产品,那么这样做是有可能的。否则,全局样式几乎是不可避免的。

并不是说这不是二元决定。许多现有的 CSS 框架并不是专门为 React 编写的,并且不能很好地与 React 鼓励的 CSS-in-JS 方法配合使用。

关于javascript - 使用 Create React App 进行 React 样式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48255464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com