【问题标题】:how to use react-native-root-toast as component in typescript如何在打字稿中使用 react-native-root-toast 作为组件
【发布时间】:2022-01-21 20:01:30
【问题描述】:

我正在使用 Typescript 开发 React Native 项目,并希望将 react-native-root-toast 创建为组件,这是我的组件代码:

import React, { memo, useEffect, useState } from "react";
import Toast from "react-native-root-toast";

interface Props {
  message: string;
  shadow?: boolean;
  textColor?: string;
}

const Component = ({ message, shadow, textColor }: Props) => {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    setTimeout(() => setVisible(true), 100);
    setTimeout(() => setVisible(false), 5000);
  }, []);

  return (
    <Toast
      visible={visible}
      position={105}
      textColor={textColor || "black"}
      shadow={shadow}
      animation={false}
      hideOnPress
    >
      {message}
    </Toast>
  );
};

Component.defaultProps = {
  shadow: true,
};

export default memo(Component);

这就是我调用组件的方式

const _btnAction = () => {
    return (
      <Toast
        message={`${product.name} (${product.colorname}, ${findSizeName(
          form.size
        )}, ${form.qty}pcs) has been added to your cart.`}
      />
    );
  };

...
...
...
<Button onPress={_btnAction} />

但它不起作用,在 Typescript 中创建 react-native-root-toast 作为组件的正确方法是什么??

干杯!

【问题讨论】:

  • &lt;Button onPress={_btnAction} /&gt; 按钮回调的返回值被忽略。它不知道如何显示您的组件。

标签: android ios typescript react-native toast


【解决方案1】:

试试这样的:

const Toaster = ({}) => {
  const [visible, setVisible] = useState(false);

  useEffect(() => if (visible) setTimeout(() => setVisible(false), 3000), [visible]);

  return <>
    {children(() => setVisible(true))}
    {visible ? <Toast ... /> : null}
  </>
};

const App = () => {
  return <Toaster>
    {toast => <Button onPress={toast} />}
  </Toaster>;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2019-06-04
    相关资源
    最近更新 更多