【问题标题】:React hooks can't work inside storybook for react nativeReact hooks 不能在 storybook 中用于 react native
【发布时间】:2022-01-09 04:14:03
【问题描述】:

技术

  • 反应(17.0.2)
  • React Native(0.66.4)
  • TypeScript(4.4.4)
  • 故事书
    • @storybook/react-native(5.3.25)
    • @storybook/react-native-server(5.3.23)

我所面临的

我的 Storybook 中出现以下反应挂钩错误。

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

我遇到错误的源代码

import React, { useState } from "react";
import { Button, Text, View } from "react-native";
import { storiesOf } from "@storybook/react-native";
import CenterView from "../../../storybook/stories/CenterView";
import Modal from "react-native-modal";

storiesOf("components/modal", module)
  .addDecorator(getStory => <CenterView>{getStory()}</CenterView>)
  .add("Modal", () => {
    const [isVisible, setIsVisible] = useState<boolean>(false); // This line doesn't work
    return (
      <View>
        <Button title={"Open Modal"} onPress={() => setIsVisible(true)} />
        <Modal
          isVisible
        >
          <Text>This is modal</Text>
        </Modal>
      </View>
    );
  });

我知道这条线是错误的原因,但我不知道如何解决这个问题。

:

const [isVisible, setIsVisible] = useState<boolean>(false); // This line doesn't work

:

【问题讨论】:

    标签: reactjs typescript react-native storybook


    【解决方案1】:

    错误正在发生,因为钩子不能在 React 组件之外调用。我建议使用控件来打开 Modal,并让 Storybook 处理状态。

    要使其按原样工作,您应该能够实现一个包装器组件并将其用作故事的第二个参数:

    storiesOf("components/modal", module)
      .addDecorator(getStory => <CenterView>{getStory()}</CenterView>)
      .add("Modal", () => <StoryWrapper />);
    
    function StoryWrapper() {
      const [isVisible, setIsVisible] = useState<boolean>(false);
    
      return (
        <View>
          <Button title={"Open Modal"} onPress={() => setIsVisible(true)} />
          <Modal isVisible={isVisible}>
            <Text>This is modal</Text>
          </Modal>
        </View>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-06
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 2020-11-19
      • 2020-03-12
      • 2019-12-24
      • 2021-11-24
      • 1970-01-01
      相关资源
      最近更新 更多