簡體   English   中英

如何使用 reactjs 和樣式組件使組件尺寸變化

[英]how to make component size variation with reactjs and styled components

如何通過“小”或“中”按鈕的道具創建變化?

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

我如何使用它來更改組件的大小?

這實際上取決於您用於設置組件樣式的內容。 例如,如果您只使用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} />
};

您可以將大小用作 class 並在樣式表中為每個 class 定義大小。

Class 組件

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM