javascript - 如何从组件容器中设置 React 组件的样式?

标签 javascript css reactjs

我有一个要从 App.jsx 路由到的组件。我希望在这个特定组件的所有边上填充 10%。对于其他组件,我希望填充为零。我已经尝试从组件内部设置样式,但它只会在两侧添加空格。我希望它的两侧是灰色的,就像页脚一样。

我尝试为我的 App.jsx 中的元素创建一个类名,然后编辑 css 样式表,但它没有改变任何东西。

在 App.jsx 中: <Route exact path="/" component={Home} className={styles.home} />

在 CSS 样式表中: .home { padding: 10%; }

在 Home 组件中,padding 设置为零,高度设置为 100vh。

我有一个内容 div,它用我的所有路由包装了 Switch 语句。无论我用这个设置填充,它都适用于我的所有组件。我只希望一个组件具有单独的填充。

最佳答案

条件样式

如果你想让某个组件根据路由有额外的样式(例如,只在根路由"/"),你可以从组件内部检查当前路由并改变相应的 CSS 样式。您可以通过将组件包装在来自 React Router 的高阶组件 withRouter 中以获取 location Prop 来实现此目的。

例如:

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';

class MyComponent extends Component {
    getClassName() {
        const { location } = this.props;

        if (location.pathname === "/") {
            return "home";
        } else {
            return "";
        }
    }

    render() {
        const className = this.getClassName();

        return (
            <div className={ className }>
                { /* whatever goes in here */ }
            </div>
        )
    }
}

export default withRouter(MyComponent);

灰色填充

您还提到您希望填充为灰色。填充不能着色,但您可以做的是将组件的呈现内容包装在另一个具有灰色背景色的 HTML 元素中。然后将 padding 放在最大的元素上。

或者,如果适用于您的用例,您可以只使用边框。

例子:

.container {
  background-color: gray;
  padding: 2rem;
}

.content {
  background-color: white;
  padding: .5rem;
}
<div class="container">
  <div class="content">
    <strong>Content</strong>
    
    <p>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
  </div>
</div>

关于javascript - 如何从组件容器中设置 React 组件的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54174412/

相关文章:

javascript - leaflet.js 标记未显示

javascript - IE8 是否支持 javascript .map() 函数?

使用适用于 Roku 的 Marmalade SDK 进行 JavaScript/HTML 开发

css - 在 jQuery Mobile 中使 div 键盘可滚动?

asp.net - ASP.NET 应用程序中的浏览器缓存

javascript - 如何避免立即验证使用 formy-react 构建的表单元素?

css - 如何对齐 React Flexbox 中的文本?

javascript - jQuery 在两个单独的 div 中按类名选择复选框

css - 总是满足于待在下一个 child 的中间?

javascript - `this` 在高阶组件中如何工作?