inile stlyes 无法在 React 解构的道具上工作如何修复?

问题描述 投票:0回答:1

你好,我正在制作一个圆形组件,我正在使用具有绝对值的道具制作内联 css,但道具不适用于该组件。

CSS



.circle{
    background-color: brown;
    width: 10rem;
    height: 10rem;
    border-radius: 50%;
    position: absolute;
    display: grid;
}

jsx


const Cirlce = ({
color ='red',
 bottom='unset',
  right='unset',
   left='unset',
     top='unset',
       index,
        children
}) => {
    return ( 
        <>
        <div className="circle" style={{
backgroundColor: {color}, 
 bottom: {bottom} , 
  left: {left} , 
   right: {right} , 
    top: {top} , 
     zIndex : {index}
}} >{children}</div>
        </>
     );
}
 
css reactjs react-props prop
1个回答
0
投票

我没有测试过,但我相信你使用道具的方式是不正确的。例如,如果您将

"unset"
传递给
bottom
属性,它将被解释为:
bottom: {bottom: "unset"}
,这不是您打算做的。正确的做法如下:

const Cirlce = ({
    color ='red',
    bottom='unset',
    right='unset',
    left='unset',
    top='unset',
    index,
    children
}) => {
    return ( 
        <>
            <div className="circle" style={{
                backgroundColor: color, 
                bottom: bottom, 
                left: left, 
                right: right, 
                top: top, 
                zIndex: index
            }}>{children}</div>
        </>
     );
}

更好的方法如下,因为对象键和值变量具有相同的拼写:

const Cirlce = ({
    color ='red',
    bottom='unset',
    right='unset',
    left='unset',
    top='unset',
    index,
    children
}) => {
    return ( 
        <>
            <div className="circle" style={{
                backgroundColor: color, 
                bottom, 
                left, 
                right, 
                top, 
                zIndex: index
            }}>{children}</div>
        </>
     );
}
© www.soinside.com 2019 - 2024. All rights reserved.