You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中Native Base FAB组件出现TransformError求助

解决React Native中Native Base FAB组件的TransformError错误

我帮你排查出这个TransformError的问题啦,主要是两个关键错误导致的:

问题根源

  • 构造函数未调用super():在React类组件的构造函数里,必须先调用super(props)才能使用this,不然会触发上下文绑定错误,这也是你报错指向第3-4行的核心原因。
  • state初始化错误:你把active的初始值写成了字符串'true',但Native Base的FAB组件active属性需要的是布尔值true/false;而且this.state的赋值必须放在super()之后才能生效。

修正后的完整代码

import React, { Component } from 'react'; 
import { Container, Header, View, Button, Icon, Fab } from 'native-base'; 

export default class FABExample extends Component { 
  constructor(props) { 
    super(props); // 先调用super,确保this可正常绑定
    this.state = { active: true }; // 改为布尔值true,去掉多余引号
  } 

  render() { 
    return ( 
      <Container> 
        <Header /> 
        <View style={{ flex: 1 }}> 
          <Fab 
            active={this.state.active} 
            direction="up" 
            containerStyle={{ }} 
            style={{ backgroundColor: '#5067FF' }} 
            position="bottomRight" 
            onPress={() => this.setState({ active: !this.state.active })}
          > 
            <Icon name="share" /> 
            <Button style={{ backgroundColor: '#34A34F' }}> 
              <Icon name="logo-whatsapp" /> 
            </Button> 
            <Button style={{ backgroundColor: '#3B5998' }}> 
              <Icon name="logo-facebook" /> 
            </Button> 
            <Button disabled style={{ backgroundColor: '#DD5144' }}> 
              <Icon name="mail" /> 
            </Button> 
          </Fab> 
        </View> 
      </Container> 
    ); 
  } 
}

优化小建议

如果你使用的是React 16.8+版本,还可以省略构造函数,直接用类属性初始化state,代码会更简洁:

import React, { Component } from 'react'; 
import { Container, Header, View, Button, Icon, Fab } from 'native-base'; 

export default class FABExample extends Component { 
  // 直接初始化state,无需构造函数
  state = { active: true }; 

  render() { 
    // 后续代码和上面一致即可
  } 
}

内容的提问来源于stack exchange,提问作者ajithes1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:40:01