代码之家  ›  专栏  ›  技术社区  ›  LOTUSMS

连接React中style={{}中的props和静态值

  •  0
  • LOTUSMS  · 技术社区  · 7 年前

    我有一个组件,我传递一个高度作为道具,这样它就可以像so一样在页面级别使用(缩小代码)

    <Component style={{height}} />
    
    Component.propTypes = {
       height: PropTypes.string, //make sure it's a string
    }
    
    Component.defaultProps = {
       height: "100%", //100% otherwise defined
    }
    

    以后可以用作

    <Component height="100%"/>
    <Component height="50%"/>
    <Component height="20%"/>
    ...
    

    并呈现为

    <div class="component-blah-blah" styles="height: 100%;"></div>
    

    我想补充 overflow-x: hidden 但作为一个默认和不可改变的道具。所以不管他们如何使用样式道具,它总是执行overflow-x I default。就像这样:

    <Component height="100%"/>
    <div class="component-blah-blah" styles="height: 100%; overflow-x:hidden"></div>
    
    <Component height="50%"/>
    <div class="component-blah-blah" styles="height: 50%; overflow-x:hidden"></div>
    
    <Component height="20%"/>
    <div class="component-blah-blah" styles="height: 20%; overflow-x:hidden"></div>
    

    我知道我可以使用-->`<-和$符号将类串联在字符串和属性中,但不能像样式要求的那样使用双括号。

    我在找这样的语法

    className='${classes.myPropClass} myCSSclass' 
    

    呈现为 class="myPropClass myCSSclass" ,但对于内联样式,不是类…并且我不能将溢出分配给类。因为其他复杂的原因

    2 回复  |  直到 7 年前
        1
  •  1
  •   trixn    7 年前

    这个 style 道具拿走一个物体。内支架 {} 只是用于创建对象内联的语法。因此,只需在render函数中向该对象添加所需的属性:

    const Component = ({height}) => (
        <div class="component-blah-blah" styles={{height, overflowX: 'hidden'}}></div>
    );
    
        2
  •  0
  •   Adam Nathaniel Davis    7 年前

    您给出的示例代码似乎与随附的描述不匹配。你说(强调,我的):

    所以不管怎样 如何使用样式道具 ,它将始终执行我默认的overflow-x。

    但你放在这里的代码并没有显示 style 道具。它只是显示出 height 道具。如果此组件的用户只被赋予 高度 使用道具,这个值不可能覆盖你的 overflowX 样式属性。

    但是 ... 如果你想让消费者进来 道具中的自己风格的物件 ,然后确保它们不会覆盖您实现 溢流 功能,您应该使用扩展运算符有效地将用户的样式与您的样式连接起来,同时防止样式被覆盖。它看起来像这样:

    class App extends Component {
      render() {
        const styleFromProps = { display: 'none' };
        return (
          <p
            style={{
              ...styleFromProps,
              display: 'inherit',
            }}
          >
            Is this displayed???
          </p>
        );
      }
    }
    
    render(<App />, document.getElementById('root'));
    

    下面是一个实例:

    https://stackblitz.com/edit/react-spread-operators-in-styles

    注意在这个例子中 styleFromProps 对象具有 display 价值 none . 但是 <p> 标签仍然显示。因为 显示 在样式对象中列出 在传入的显示值之后 . 在CSS中,如果一个属性声明了两次,则最后一个属性“获胜”。

    因此,如果允许用户将样式对象作为道具传入,但要确保它们不会覆盖正在使用的某些“关键”样式,则可以这样做。