gpt4 book ai didi

javascript - 对样式组件使用 propTypes 和 defaultProps

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:41:20 25 4
gpt4 key购买 nike

以下样式组件抛出错误:

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)

工作版本

当我注释掉组件的 propTypesdefaultProps 时,它能够呈现某种按钮。

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

这要求每个样式化的组件都需要一个额外的组件来利用 prop-types。是否有一种机制或替代 API 允许我使用样式化组件而无需将其包装在其他组件中。

最佳答案

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.
}

style property always eexpect object with {key : value} 其中键是 css 属性,值是这些键的任何有效 css 值

例如

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

关于javascript - 对样式组件使用 propTypes 和 defaultProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45977114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com