【问题标题】:how to make component size variation with reactjs and styled components如何使用 reactjs 和样式化组件使组件大小变化
【发布时间】:2021-07-05 07:21:27
【问题描述】:

如何通过“小”或“中”按钮的道具创建变体?

interface Props {
  size?: 'medium' | 'small';
}

如何使用这个来改变组件的大小?

【问题讨论】:

    标签: javascript reactjs typescript styled-components


    【解决方案1】:

    这实际上取决于您使用什么来设置组件的样式。例如,如果您只使用 style 道具,您可以执行以下操作:

    interface Props {
      size?: 'medium' | 'small'
    }
    
    const Component = ({ size }: Props) => {
      return <div style={{ width: size === 'medium' ? 50 : 25 }} />
    };
    

    或者,如果您使用 CSS,请使用 https://github.com/JedWatson/classnames 之类的内容轻松地在您的类之间切换:

    interface Props {
      size?: 'medium' | 'small'
    }
    
    const Component = ({ size }: Props) => {
      const className = classNames({
        [styles.medium]: size === 'medium',
        [styles.small]: size === 'small',
      });
    
      return <div className={className} />
    };
    

    【讨论】:

      【解决方案2】:

      您可以将大小用作一个类,并在样式表中为每个类定义大小。

      类组件

      import './styles.css';
      
      class YourComponent extends React.Component {
          ...
      
          render() {
              ...
              <div class={this.props.size ? this.props.size : null}>
                  ...
              </div>
              ...
          }
      }
      

      功能组件

      import './styles.css';
      
      const YourComponent = (props: Props) => {
          ...
          return (
              ...
              <div class={props.size ? props.size : null}>
                  ...
              </div>
              ...
          );
      }
      

      styles.css

      .medium {
          width: 100px; // width for medium size
          height: 40px; // height for medium size
      }
      
      .small {
          width: 60px; // width for small size
          height: 20px; // height for small size
      }
      

      【讨论】:

        猜你喜欢
        • 2020-09-26
        • 2020-09-22
        • 2021-07-04
        • 2017-07-04
        • 2018-11-20
        • 2021-11-01
        • 1970-01-01
        • 2021-12-21
        • 2021-07-02
        相关资源
        最近更新 更多