【问题标题】:Typescript extend react native View component打字稿扩展反应原生视图组件
【发布时间】:2019-09-26 01:49:39
【问题描述】:

试图扩展 react-native View 组件。但是我在扩展 View 组件的 props 时遇到了问题。

这是我扩展Props的方法

import { StyleSheet, View, ViewStyle, ViewProps } from "react-native";
interface Props extends ViewProps {
  pb?: keyof Size | number;
  pt?: keyof Size | number;
  pv?: keyof Size | number;
  ph?: keyof Size | number;
}

这是我自定义的View 组件

class WrappedView extends Component<Props> {
  render() {
    const methods = {};
    let { style: attrStyles, children, pb, pt, pv, ph, ...rest } = this.props;
    let style = [attrStyles];
    // Shorthand prop styles
    let propStyles: ViewStyle = {};
    propStyles.paddingBottom = pb;
    propStyles.paddingTop = pt;
    propStyles.paddingVertical = pv;
    propStyles.paddingHorizontal = ph;
    style.push(propStyles);
    return (
      <View style={style} {...rest} {...this.state} {...methods}>
        {children}
      </View>
    );
  }
}

当我尝试这样的测试时

const test = () => {
  return <WrappedView pb={"large"} width={"100%"} />;
};

我收到以下问题

Type '{ pb: "large"; width: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<WrappedView> & Readonly<Props> & Readonly<{ children?: ReactNode; }>'.
  Property 'width' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<WrappedView> & Readonly<Props> & Readonly<{ children?: ReactNode; }>'.

【问题讨论】:

  • width 不是来自ViewProps 的道具。检查它here
  • 啊,这太尴尬了,谢谢

标签: typescript react-native typescript-typings


【解决方案1】:

问题中的代码确实正确扩展了道具,而不是客户端错误。客户应阅读:

const test = () => {
  return <WrappedView pb={"large"} style={{width:"100%"}} />;
};

【讨论】:

  • 没错。请注意,您不需要像在问题中那样在 interface Props extends ViewProps 中重新定义 style 属性,因为样式已经是 ViewProp
猜你喜欢
  • 1970-01-01
  • 2017-06-18
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多