[英]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 定義大小。
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.