如何解决如果使用打字稿的某些条件为真,如何更改添加页边距的底部和页边距右并做出反应?
我具有如下所示的组件,当isOpen状态为true时,应添加margin-top 0,margin-bottom:0,margin-right和margin-left:4px。如果isOpen状态为false,则添加margin-right:4px和margin-bottom:4px。
下面是我的代码,
function Parent() {
return (
<Wrapper isOpen={isOpen}/>
//Some content
</Wrapper>
);
}
const Wrapper = styled(somediv)<{ isOpen: boolean | undefined;}>`
width: ${props => (props.isOpen ? '32px' : '40px')};
margin: 0 4px; //should modify this based on isOpen true or not.
`;
有人可以帮我吗?谢谢。
解决方法
像这样吗?
<Wrapper isOpen={isOpen} style={{ isOpen===true?
{marginRight:'0px';marginLeft:'4px'} : {marginRight:'4px';marginLeft:'4px';} }}/>
//Some content
</Wrapper>
,
最简单的方法可能是创建两个对象,每个对象具有不同的属性,并以内联样式添加它们。
const styles1 = {};
const styles2 = {};
<Wrapper style={{isOpen ? styles1 : styles2}}/>
//Some content
</Wrapper>
,
我不确定我是否理解正确,但是使用三元运算符应该看起来像这样
const Wrapper = styled(somediv)<{ isOpen: boolean | undefined;}>`
width: ${props => (props.isOpen ? '32px' : '40px')};
margin: ${props => (props.isOpen ? '0 4px' : '0 4px 4px 0')}
`;
,
使用与您相同的样式化组件方法。 它将像下面这样工作:
function Parent() {
return (
<Wrapper isOpen={isOpen}/>
//Some content
</Wrapper>
);
}
const Wrapper = styled(somediv)<{ isOpen: boolean | undefined;}>`
width: ${props => (props.isOpen ? '32px' : '40px')};
margin: ${props => (props.isOpen ? '0 4px' : '0 4px 4px 0')};
`;
,
如果您想使用className而不是内联样式,建议您按以下方式使用makeStyles from Material UI
// with npm
npm install @material-ui/styles
然后
import React,{useState} from 'react';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
myClass: {
marginBottom: isOpen => isOpen ? 4 : 0,marginTop: 4,width: isOpen => isOpen ? 32 : 40
}
}))
const Parent = () => {
const [isOpen,setOpen] = useState(false)
const classes = useStyles(isOpen)
return <div className={classes.myClass} />
}
然后,您可以将其用于其他属性和类。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。