【问题标题】:Flow with Rest Object in a functional component在功能组件中使用 Rest Object 流
【发布时间】:2020-04-24 21:40:33
【问题描述】:

我正在制作一个处理各种属性的功能组件,我们可以使用 Rest 对象将其他基本属性传递给该组件。

事实是我遇到了 2 个流错误:

  • 无法创建 TouchableOpacity 元素,因为不精确的道具 [1] 不兼容 使用精确的 Props [2]。
  • 无法获取 props.style,因为对象的其余部分缺少属性样式 模式 [1]。

这是我的代码:

type Props = {
  text: string,
  textColor: string,
  backgroundColor: string,
  handleClick: () => void,
};

const Button = ({
  textId,
  textColor,
  backgroundColor,
  handleClick,
  ...props
}: Props) => {
  const {t} = useTranslation();

  const styles = {
    button: {
      padding: 10,
      backgroundColor: backgroundColor,
    },
    text: {
      color: textColor,
      textAlign: 'center',
      fontWeight: 'bold',
    },
  };

  return (
    <TouchableOpacity
      {...props}
      style={[styles.button, props.style]}
      onPress={handleClick}>
      <Text style={styles.text}>{t(textId)}</Text>
    </TouchableOpacity>
  );
};

我怎样才能有一个正确的方法来输入我的 Rest Object ...props ?

谢谢。

【问题讨论】:

    标签: reactjs react-native flowtype


    【解决方案1】:

    您可以通过执行以下操作来确定类型:

    type Props =  $Exact<{
      text: string,
      textColor: string,
      backgroundColor: string,
      handleClick: () => void,
    }>;
    

    这应该可以解决您的第一个错误。

    至于第二个错误,我认为在 Props 类型中添加 style 作为条目应该可以解决该问题。

    【讨论】:

      猜你喜欢
      • 2018-03-31
      • 2021-07-14
      • 1970-01-01
      • 2021-08-02
      • 2021-07-12
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 2023-03-24
      相关资源
      最近更新 更多