我在React应用程序(使用create-react-app创建)中使用样式化组件时遇到了一些麻烦,在这里我也使用了Material-ui。
我是样式组件的新手,所以我试图为基于另一个Material-UI组件的样式组件内的Material-UI组件设置样式。为了阐明我要做什么,下面是代码:
const StyledContainer = styled(Container)`
background-color: ${props=>props.theme.defaultBackground};
${FormControl} {
width:100%;
}
`;
Container和FormControl确实是material-ui组件。
现在我知道我不应该在父母中为孩子们称呼,但正如我所说,我只是在练习。
当我这样做并使用StyleContainer时,出现PropType错误:
Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at ...
这是堆栈跟踪:
checkType
node_modules/prop-types/factoryWithTypeCheckers.js:181
flatten
http://localhost:3000/static/js/0.chunk.js:226001:21
ComponentStyle.generateAndInjectStyles
http://localhost:3000/static/js/0.chunk.js:226243:27
useInjectedStyle
http://localhost:3000/static/js/0.chunk.js:226460:120
useStyledComponentImpl
http://localhost:3000/static/js/0.chunk.js:226488:28
Styled(WithStyles(ForwardRef(Container)))
http://localhost:3000/static/js/0.chunk.js:226555:12
renderWithHooks
node_modules/react-dom/cjs/react-dom.development.js:14803
updateForwardRef
node_modules/react-dom/cjs/react-dom.development.js:16816
beginWork
node_modules/react-dom/cjs/react-dom.development.js:18645
HTMLUnknownElement.callCallback
node_modules/react-dom/cjs/react-dom.development.js:188
invokeGuardedCallbackDev
node_modules/react-dom/cjs/react-dom.development.js:237
invokeGuardedCallback
node_modules/react-dom/cjs/react-dom.development.js:292
beginWork$1
node_modules/react-dom/cjs/react-dom.development.js:23203
performUnitOfWork
node_modules/react-dom/cjs/react-dom.development.js:22154
workLoopSync
node_modules/react-dom/cjs/react-dom.development.js:22130
performSyncWorkOnRoot
node_modules/react-dom/cjs/react-dom.development.js:21756
scheduleUpdateOnFiber
node_modules/react-dom/cjs/react-dom.development.js:21188
updateContainer
node_modules/react-dom/cjs/react-dom.development.js:24373
(anonymous function)
node_modules/react-dom/cjs/react-dom.development.js:24758
unbatchedUpdates
node_modules/react-dom/cjs/react-dom.development.js:21903
legacyRenderSubtreeIntoContainer
node_modules/react-dom/cjs/react-dom.development.js:24757
render
node_modules/react-dom/cjs/react-dom.development.js:24840
您能帮我解决这个问题吗!
谢谢!
答案 0 :(得分:1)
如果被引用的组件是样式组件,则只能引用另一个组件内部的组件。来自docs:
仅在样式化组件的上下文中支持此行为:在以下示例中尝试安装B将失败,因为组件A是React.Component的实例,而不是样式化组件。
引发错误-无法将类作为函数调用-发生的原因是样式化的组件正试图将其作为内插函数调用。
但是,将A包裹在styled()工厂中使其可以进行插值-只需确保包裹的组件沿className传递即可。
也就是说:
const StyledFormControl = styled(FormControl);
const StyledContainer = styled(Container)`
background-color: ${props=>props.theme.defaultBackground};
${StyledFormControl} {
width:100%;
}
`;