【问题标题】:styled-components toggle classes样式组件切换类
【发布时间】:2023-04-02 08:44:01
【问题描述】:

this.state.checkBool 是 true / false

这样的HTML结构,切换class1class2

<div class='common class1'>
<div class='common class2'>

css 看起来像

common {
  display: block;
  background: grey;
}

.class1 {
  position: absolute;
  left: 1px;
  right: auto;
  top: 2px;
  background: blue;
}


.class2 {
  position: absolute;
  left: auto;
  top: 2px;
  right: 30px;
  background: yellow;
}

样式化组件

const Wrapper = styled.div`
  display: block;
  background: grey;

  // Should this part use props to check true or false?

  ${prosp => } 
`

我被困在如何切换类

<Wrapper toggle={this.state.checkBool ? class1 :class2 }/>

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    您希望将所有 CSS 保留在 styled.div 中,并使用 toggle 属性根据其值决定您应该为组件使用哪个 CSS。

    示例

    const Wrapper = styled.div`
      display: block;
      background: grey;
      ${props => {
        if (props.toggle) {
          return `
            position: absolute;
            left: 1px;
            right: auto;
            top: 2px;
            background: blue;
          `;
        } else {
          return `
            position: absolute;
            left: auto;
            top: 2px;
            right: 30px;
            background: yellow;
          `;
        }
      }}
    `;
    
    class App extends React.Component {
      state = { checkBool: false };
    
      componentDidMount() {
        setTimeout(() => {
          this.setState({ checkBool: true });
        }, 1000);
      }
    
      render() {
        return <Wrapper toggle={this.state.checkBool}> Foo </Wrapper>;
      }
    }
    
    ReactDOM.render(<App />, document.getElementById("root"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>
    
    <div id="root"></div>

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 2020-04-17
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      • 1970-01-01
      • 2019-09-01
      • 1970-01-01
      相关资源
      最近更新 更多