React Native styled-components中如何从父组件样式化子组件?
React Native 中从父组件样式化子组件的解决方案
因为 React Native 环境下 styled-components 不支持 CSS 选择器(比如 & > * 这类后代选择器),你可以用以下几种替代方案实现父组件控制子组件样式:
方法一:通过 props 传递样式给子组件
在父组件中定义子组件需要的样式,通过 props 传递给子组件,子组件接收后合并到自身样式中。
// 父组件样式 const Container = styled(Block)` flex-direction: column; `; // 修改子组件,支持接收外部样式 props const Container2 = styled(Block)` /* 子组件原有基础样式 */ ${props => props.parentStyle}; `; // 使用时传递父组件定义的样式 <Container> {[1, 2, 3].map((el) => { return ( <Container2 key={el} parentStyle={` background: black; flex: initial; margin-right: 0; border-bottom-width: 5px; border-bottom-color: white; `} > <Text>{el}</Text> </Container2> ) })} </Container>
方法二:直接定义子组件的样式变体
在父组件所在文件中,基于原有 Container2 创建一个带父控样式的变体组件,直接使用这个变体:
// 原有基础子组件 const Container2 = styled(Block)` /* 子组件原有样式 */ `; // 父组件中定义子组件的样式变体 const StyledContainer2 = styled(Container2)` background: black; flex: initial; margin-right: 0; border-bottom-width: 5px; border-bottom-color: white; `; // 父组件样式 const Container = styled(Block)` flex-direction: column; `; // 使用样式变体 <Container> {[1, 2, 3].map((el) => { return ( <StyledContainer2 key={el}> <Text>{el}</Text> </StyledContainer2> ) })} </Container>
方法三:使用 ThemeProvider 共享样式
如果需要让多个组件复用这套父控样式,可以把样式放到主题中,子组件从主题读取样式:
// 定义全局主题 const theme = { childContainerStyle: ` background: black; flex: initial; margin-right: 0; border-bottom-width: 5px; border-bottom-color: white; ` }; // 子组件从主题获取样式 const Container2 = styled(Block)` /* 子组件原有样式 */ ${props => props.theme.childContainerStyle}; `; // 父组件样式 const Container = styled(Block)` flex-direction: column; `; // 在上层组件包裹 ThemeProvider <ThemeProvider theme={theme}> <Container> {[1, 2, 3].map((el) => { return ( <Container2 key={el}> <Text>{el}</Text> </Container2> ) })} </Container> </ThemeProvider>
内容的提问来源于stack exchange,提问作者DevOverflow
相关产品推荐
相关产品推荐

