【问题标题】:ReactJs re-use same component but with different stylesReactJs 重用相同的组件,但样式不同
【发布时间】:2018-10-19 20:39:19
【问题描述】:

我有一个希望在 reactJs 中重复使用的按钮组件,我希望渲染多个相同的组件,但使用不同的样式,并在按下按钮和鼠标悬停时使用不同的样式

按钮组件是:-

import React, { Component } from 'react';
//import './Buttons.css'
const buttons = (props) => {



    return (
      <div className="">

        <button id="buttons" class="-"> {props.name}</button>

        </div>

    );
  }


export default buttons;

主 App 组件持有一个状态,然后该状态显示按钮的名称,我相信有更好的方法来做到这一点。

我还制作了多个按钮组件,我可以通过这种方式应用 css 样式,但我确信这不是正确的方式。

class App extends Component {



  state = {
    name: [
      { button: 'Login' },
      { buttonTwo: 'Sign Up' },
      { buttons: 'Login' }
    ],

  }
  render() {

    const style = {
      backgroundColor: 'blue',
      font: 'inherit',
      border: '1px solid red',
      padding: '8px',

    };



    var pressed = true
    function toggle() {
      pressed = !pressed

      //When pressed Styles change
    }

    return (
      <div className="App">

       {/* <Right />  Temp Disabled*/}
        <span><Button pressed={pressed} defaultPressed={true} pressedStyle={{color: 'blue'}}
        name={this.state.name[0].button} /></span>
        <span><Button name={this.state.name[1].buttonTwo} /></span>

      </div>
    );
  }
}

export default App;

我最终的目标是创建一个登录部分,以便这些按钮成为其中的一部分。

【问题讨论】:

  • 将类作为道具传递给组件

标签: javascript css reactjs


【解决方案1】:

为什么不只使用 CSS 并使用原生 :active:hover 伪类来处理“鼠标悬停”和“按下按钮”?如果您的样式将在 CSS 中,那么您可以将一些字符串作为参数传递(例如 className)并在 .css 文件中简单地定义必要的样式

例如

class Application extends React.Component {
  render() {
    return (
      <div className="application-wrapper">
        <Button className="red">This is the red button</Button>
        <Button className="blue">This is the blue button</Button>
      </div>
    )
  }
}

class Button extends React.Component {
  render() {
    return (
      <button className={`my-awesome-button ${this.props.className}`}>{this.props.children}</button>
    )
  }
}

ReactDOM.render(<Application />, document.getElementById("kappa"))
.my-awesome-button {
  line-height: 40px;
  padding: 0 20px;
  border: none;
  background: black;
  color: white;
  font-weight: bold;
  cursor: pointer;
  outline: none;
}

.my-awesome-button:hover {
  opacity: .54
}

.my-awesome-button:active {
  opacity: .38
}

.my-awesome-button.red {
  background: red
}

.my-awesome-button.blue {
  background: blue
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="kappa"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 2020-08-14
    相关资源
    最近更新 更多