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

React Native餐厅星级评分组件报错ReferenceError: Stars is not defined问题排查及代码修复

Fixing "ReferenceError: Stars is not defined" in React Native Star Rating Component

Hey there, let's get that star rating component up and running without errors! That ReferenceError: Stars is not defined you're hitting has a simple, clear fix.

What's Causing the Error?

The problem stems from how you tried to export your component. When you wrote export default Stars = ({ rating }) => { ... }, you were assigning an arrow function to a variable Stars that hadn't been declared first. React Native uses JavaScript's strict mode by default, which doesn't allow this kind of implicit global variable creation—you need to explicitly define the variable before using it.

Fixed Component Code

Here's the corrected version of your star rating component:

import React from 'react';
import { View } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';

// First declare the Stars component explicitly
const Stars = ({ rating }) => {
  const stars = [...Array(Math.ceil(rating))];
  return (
    <View style={{ flexDirection: 'row' }}>
      { stars.map((_, i) => {
        const name = Math.floor(rating) > i ? 'star' : 'star-half';
        return <Icon key={i} name={name} color="#FFD64C" />
      }) }
    </View>
  )
}

// Then export it as the default export
export default Stars;

Key Fix Breakdown

All we changed was adding a const declaration for Stars before assigning the component function to it, then exporting it separately. This properly tells JavaScript what Stars refers to, eliminating the reference error entirely. Your logic for rendering full and half stars stays exactly the same—this just fixes the variable declaration/export issue that was blocking your component from running.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 08:28:12