React Native使用styled-components报TypeError undefined is not a function如何解决
报错产生原因
- React Native 环境不存在浏览器端的 HTML 原生标签,你使用的
styled.button是web版styled-components的API,不适用于RN场景,对应的方法不存在才会触发类型错误。 - 额外的不兼容问题:你代码中写的
bordercolor是非法样式属性名,正确写法是驼峰式borderColor;web端的:hover伪类在RN原生环境也不生效,RN原生没有hover交互的原生支持。
修复方案
- 调整styled-components的导入路径,使用RN专属的导出:
import styled from "styled-components/native"; - 替换
styled.button为包裹RN原生可点击组件的写法,优先使用Pressable或者TouchableOpacity这类RN内置的交互组件,修复后参考代码如下:
import styled from "styled-components/native"; import { Pressable } from 'react-native'; const Buttonn = styled(Pressable)` background: white; width: 200px; height: 50px; border-color: black; border-width: 1px; justify-content: center; align-items: center; `; const ButtonText = styled.Text` font-size: 24px; color: black; `; function CourierDetails() { return ( <Buttonn // 按压变色效果可以通过Pressable自带的状态回调实现 style={({ pressed }) => pressed && { backgroundColor: 'black' }} > <ButtonText style={({ pressed }) => pressed && { color: 'white' }} > Submit </ButtonText> </Buttonn> ) }
- 注意补充RN必填的边框样式属性,比如
border-width,仅写边框颜色不会生效。
内容的提问来源于stack exchange,提问作者Mayanka Rote
相关产品推荐
相关产品推荐

