【问题标题】:How to apply different background colour and different border colour for reusable components in react?如何在反应中为可重用组件应用不同的背景颜色和不同的边框颜色?
【发布时间】:2020-04-01 06:56:34
【问题描述】:

我正在开发 react 项目,在该项目中,我有一个父组件,它是 App.js,而 Child.js 是一个子组件。

现在在 App.js 中,我调用了两次 Child.js。现在我已经为 Child.js 编写了一些 CSS,所以在输出中会出现两个圆圈。

现在我正在尝试为两个圆圈实现不同的背景颜色和不同的边框颜色

这是我的代码

这是 App.js

import React from 'react';
import './App.css';
import Child from './Child/Child';



function App() {
  return(
    <div className="App">
      <Child/>
      <Child/>
    </div>
  );
}

export default App;

这在 App.css 中什么都不是

这是 Child.js

import React from 'react';
import './Child.css';


function Child({ customstyle }) {
    return (
        <div className='container'>
            <div className='row'>
                <div className='col-12'>
                    <div className="exp">
                    </div>
                </div>
            </div>
        </div >
    )
}

export default Child

这是 Child.css

.exp {
    height: 100px;
    width: 100px;
    border-radius: 50%;
    border: 1px solid black;
}

如果我不清楚我的疑问,请发表评论

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    创建两种不同的样式。

    .exp {
        height: 100px;
        width: 100px;
        border-radius: 50%;
        border: 1px solid black;
    }
    .exp2 {
        height: 200px;
        width: 200px;
        border-radius: 20%;
        border: 1px solid blue;
    }
    

    将类名作为道具传递给子组件,并在子组件中使用它以实现不同的样式。如下:

    import React from 'react';
    import './Child.css';
    import classnames from 'classnames';
    
    function Child({ customstyle }) {
        return (
            <div className='container'>
                <div className='row'>
                    <div className='col-12'>
                        <div className={classnames(customstyle)}>
                        </div>
                    </div>
                </div>
            </div >
        )
    }
    
    export default Child
    
    

    【讨论】:

    • 嗨@Kumar Swapnil 我试过你说的,但它不起作用
    • 你是否将 props 传递给子组件作为 &lt;Child customstyle = 'exp1' /&gt; and &lt;Child customstyle='exp2' /&gt;
    • 另外,您没有将classnames 依赖项添加到您的项目中。
    • 如果可以在沙箱中给我发你的代码,我很困惑。无论如何,非常感谢。
    • 我非常感谢你@Kumar Swapnil's
    猜你喜欢
    • 2014-07-13
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 2016-05-10
    • 2016-07-13
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多