【发布时间】:2021-07-05 07:21:27
【问题描述】:
如何通过“小”或“中”按钮的道具创建变体?
interface Props {
size?: 'medium' | 'small';
}
如何使用这个来改变组件的大小?
【问题讨论】:
标签: javascript reactjs typescript styled-components
如何通过“小”或“中”按钮的道具创建变体?
interface Props {
size?: 'medium' | 'small';
}
如何使用这个来改变组件的大小?
【问题讨论】:
标签: javascript reactjs typescript styled-components
这实际上取决于您使用什么来设置组件的样式。例如,如果您只使用 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} />
};
【讨论】:
您可以将大小用作一个类,并在样式表中为每个类定义大小。
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
}
【讨论】: