[英]Using propTypes and defaultProps for a styled-component
以下樣式組件引發錯誤:
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: 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
和defaultProps
時,它能夠呈現某種按鈕。
https://www.webpackbin.com/bins/-KsrPX89Zi6MnRw9X11E
這要求每個樣式化的組件都需要使用額外的組件來利用prop-types
。 是否有機制或替代API允許我使用樣式組件而不將其包裝在其他組件中。
錯誤:
style
prop期望從樣式屬性到值的映射,而不是字符串。 例如,使用JSX時style = {{marginRight:spacing +'em'}}。 這個DOM節點由styled.button
呈現。
StyledButton.defaultProps = {
size: 'md',
style: 'primary' //is the wrong way.
}
它應該是
StyledButton.defaultProps = {
size: 'md',
style: { color : 'red'} //e.g.
}
style屬性總是eexpect對象{key : value}
其中key是css屬性,value是這些鍵的任何有效css值
例如
style : {
border: '1px solid red',
font-size: 12px,
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.