【问题标题】:Conditional component styling fails with error条件组件样式失败并出现错误
【发布时间】:2020-05-20 04:37:17
【问题描述】:

这是一个简单的样式依赖于点击。

const styles = {
  marginLeft: count * (-20) + 40 +'%'
}

如果我这样做,一切都会正常

return <div key={index} className={classnames({ 'food-photo': content })} style={styles}>

但我需要将它们设置为第一个元素,所以在地图内我得到了索引,如果我会这样做:

return <div key={index} className={classnames({ 'food-photo': content })} style={(index===0)?{styles}:''}>

我得到的错误:

_app.js:69 Uncaught Invariant Violation:style 属性需要从样式属性到值的映射,而不是字符串。例如, 使用 JSX 时 style={{marginRight: spacing + 'em'}}。

【问题讨论】:

    标签: javascript css reactjs jsx


    【解决方案1】:

    如果index 不等于0 和styles(不包含在花括号中)则传递空对象:

    return <div key={index} className={classnames({ 'food-photo': content })} style={index===0?styles:{}}>
    

    跟随 sn-p 是一个概念的快速而肮脏的证明:

    const { render } = ReactDOM
    
    const styles = {
            backgroundColor: 'blue',
            color: 'white',
            width: 50
          }
    
    const Test = ({index}) => <div style={index===0?styles:{}}>Test</div>
    
    render (
      (<div>
        <Test index={0}/>
        <Test index={1}/>
      </div>),
      document.getElementById('root')
    )
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"&gt;&lt;/script&gt;&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"&gt;&lt;/script&gt;&lt;div id="root"&gt;&lt;/div&gt;

    【讨论】:

    • no, error: _app.js:69 Uncaught Invariant Violation: style prop 需要从样式属性到值的映射,而不是字符串。例如,使用 JSX 时 style={{marginRight:spacing + 'em'}}
    • 最后 xD 我也找到了一个解决方案,通过'margin-left'而不是marginLeft xD,但保持语法应该是更好的做法
    【解决方案2】:

    只需更改 else 大小写以传递一个空对象。下面的代码可以正常工作。

    return <div key={index} className={classnames({ 'food-photo': content })} style={(index===0) ? { ...styles } : {}}>
    

    【讨论】:

    • 代码不起作用,我在控制台中也找不到错误。在 IDE 中:type '{ styles....}' 不能分配给 type 'cssproperties'
    • 可能问题出在样式中的“%”上。您可能需要传递一个数值
    • 您可以安全地将{...styles} 替换为styles(不带花括号),在这方面查看my answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 2016-08-02
    • 2016-03-14
    相关资源
    最近更新 更多