打字稿扩展反应本机视图组件

时间:2019-05-08 10:42:14

标签: typescript react-native typescript-typings

尝试扩展react-native View组件。但是我在扩展View组件的道具时遇到了麻烦。

这是我扩展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; }>'.

1 个答案:

答案 0 :(得分:0)

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

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