2017-08-31 14 views
3

以下風格的組分引發錯誤:使用propTypes和defaultProps用於樣式組分

const StyledButton = styled.button` 
    font-weight: 400; 
    vertical-align: middle; 
    text-align: center; 
    text-decoration: none; 
    white-space: nowrap; 
    margin-right: 0.2rem; 
    outline: 0; 
    cursor: pointer; 
    -webkit-user-select: none; 
    -moz-user-select: none; 
    -ms-user-select: none; 
    user-select: none; 
    -webkit-appearance: none; 
` 

const { oneOf, bool } = PropTypes 

// button has no md size 
StyledButton.propTypes = { 
    /** enable block styling on the button */ 
    block: bool, 
    /** size variant for the button */ 
    size: oneOf(['lg', 'sm', 'md']), 
    /** style variant for the button */ 
    style: oneOf(['primary', 'grey', 'darkgrey', 'link', 'danger']) 
} 

StyledButton.defaultProps = { 
    size: 'md', 
    style: 'primary' 
} 

ERROR

Error: The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX. This DOM node was rendered by `styled.button`. 
    at invariant (invariant.js?7313:44) 
    at assertValidProps (ReactDOMComponent.js?922a:152) 
    at ReactDOMComponent.mountComponent (ReactDOMComponent.js?922a:452) 
    at Object.mountComponent (ReactReconciler.js?c56c:45) 
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js?063f:370) 
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js?063f:257) 
    at Object.mountComponent (ReactReconciler.js?c56c:45) 
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js?063f:370) 
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js?063f:257) 
    at Object.mountComponent (ReactReconciler.js?c56c:45) 

工作版本

它能夠當我註釋掉propTypes和時渲染某種按鈕爲組件。

https://www.webpackbin.com/bins/-KsrPX89Zi6MnRw9X11E

這就要求每一個樣式的組件需要一個額外的組件使用採取的prop-types優勢。是否有機制或替代API允許我使用樣式化組件而不將其包裝到其他組件中。

回答

4

Error: The style prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX. This DOM node was rendered by styled.button .

StyledButton.defaultProps = { 
    size: 'md', 
    style: 'primary' //is the wrong way. 
} 

它應該是

StyledButton.defaultProps = { 
    size: 'md', 
    style: { color : 'red'} //e.g. 
} 

樣式屬性與{key : value}總是eexpect對象,其中的關鍵是CSS屬性和價值是爲那些鍵

例如在任何有效的CSS值

style : { 
    border: '1px solid red', 
    font-size: 12px, 
} 
+0

謝謝你的解釋,我知道'style'是一個保留的道具,但我沒有足夠的重視我的代碼。爲這樣一個微不足道的問題浪費你的時間道歉。 – vamsiampolu

相關問題