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

为何函数不能作为React子元素?类转函数组件报错求助

解决React报错:Functions are not valid as a React child

嘿,这个错误我之前也踩过坑,一眼就能揪出问题所在:你在JSX里直接放了函数本身,而没有调用它。

看你代码里的这部分:

return (
  <CenterView>
    {renderStory}
  </CenterView>
);

你这里写的{renderStory}是把整个函数对象传给了React,让它当作子元素渲染,但React根本不认识函数类型的子节点,所以就抛出了那个报错。你需要做的是调用这个函数,拿到它返回的JSX内容,也就是把它改成{renderStory()}。

另外还有个容易忽略的小细节:FlatList的renderItem参数是一个包含item属性的对象,你之前的renderStoryItem(item)写法会把整个对象当成数据项,这样访问item.id其实是在访问参数对象的id,而不是你想要的故事数据的id。所以应该改成解构出item的写法:({ item })。

修改后的完整代码如下:

const ProfileStories = (props) => {
  const renderStory = () => {
    const data = props.userStory ? props.userStory.data : [];
    if (props.isClicked) {
      return (
        <FlatList
          data={data}
          renderItem={renderStoryItem}
          keyExtractor={(item, index) => index.toString()}
          numColumns={2}
        />
      );
    }
    return null;
  };
  const renderStoryItem = ({ item }) => {
    return (
      <StoryItem key={item.id} content={item.content} date={item.createdAt} />
    );
  };
  return (
    <CenterView>
      {renderStory()} {/* 这里改成调用函数 */}
    </CenterView>
  );
};
export default ProfileStories;

如果你想让代码更简洁,也可以不用单独定义renderStory函数,直接在组件里计算要渲染的内容:

const ProfileStories = (props) => {
  const data = props.userStory?.data || [];
  const storyContent = props.isClicked ? (
    <FlatList
      data={data}
      renderItem={({ item }) => (
        <StoryItem key={item.id} content={item.content} date={item.createdAt} />
      )}
      keyExtractor={(item, index) => index.toString()}
      numColumns={2}
    />
  ) : null;

  return (
    <CenterView>
      {storyContent}
    </CenterView>
  );
};
export default ProfileStories;

这样不仅解决了报错,代码结构也更清晰啦。

内容的提问来源于stack exchange,提问作者J.range

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:29:34