Issue
I want to monkeypatch react-native Text
element render function.
Typescript shows me some errors, as the exported Text
class does not expose the defaultProps
static member each instance has internally (via TouchableText implementation inside react-native) and the render
function which is also not party of the public interface.
However the code below is valid JS code (at least) and it works correctly to achieve my goal. I'd still like to get rid of the TS warnings.
const setCustomText = (customProps: TextProps) => {
Text.defaultProps = {
...Text.defaultProps,
...customProps,
}
const orgRender = Text.render
Text.render = function render(props:TextProps, ref:Ref<Text>) {
const style = Array.isArray(props.style) ? props.style : [props.style]
props = {
...props,
style: [Text.defaultProps.style, ...style],
}
return orgRender.call(this, props, ref)
}
}
It complains:
Text.defaultProps
: Property 'defaultProps' does not exist on type 'typeof Text'.ts(2339)
Text.render
: Property 'render' does not exist on type 'typeof Text'.ts(2339)
Solution
I went for this, not super proud of the :any
type, but works fine and doesn't complain, feel free to improve it and if you do, please share :)
interface TextTypescriptProps extends Text {
defaultProps?: any;
render: any;
}
export const setCustomText = (customProps: TextProps) => {
Text as unknown as TextTypescriptProps = Text as unknown as
TextTypescriptProps || {};
(Text as unknown as TextTypescriptProps).defaultProps = {
...Txt.defaultProps,
...customProps,
};
const orgRender = Txt.render;
(Text as unknown as TextTypescriptProps).render = function render(props: TextProps, ref: Ref<Text>) {
const style = Array.isArray(props.style) ? props.style : [props.style];
props = {
...props,
style: [(Text as unknown as TextTypescriptProps).defaultProps.style, ...style],
};
return orgRender.call(this, props, ref);
};
};
Answered By - ClaraG
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.