Решение, которое вы нашли, кажется единственным выходом из ситуации на данный момент. Я обновлю свой ответ. Спасибо, что дал мне знать
аюсь реализовать примерПотребление контекста с HOC из документации React (React 16.3) в TypeScript (2.8) и с треском проваливается. Для справки, код из руководства React:
const ThemeContext = React.createContext('light');
// This function takes a component...
export function withTheme(Component) {
// ...and returns another component...
return function ThemedComponent(props) {
// ... and renders the wrapped component with the context theme!
// Notice that we pass through any additional props as well
return (
<ThemeContext.Consumer>
{theme => <Component {...props} theme={theme} />}
</ThemeContext.Consumer>
);
};
}
Лучшее, что я мог придумать:
export interface ThemeAwareProps {
theme: string;
}
const ThemeContext = React.createContext('light');
export function withTheme<P extends ThemeAwareProps, S>(Component: new() => React.Component<P, S>) {
return function ThemedComponent(props: P) {
return (
<ThemeContext.Consumer>
{theme => <Component {...props} theme={theme} />}
</ThemeContext.Consumer>
);
};
}
class App extends React.Component {
public render() {
return (
<ThemeContext.Provider value={'dark'}>
<ThemedButton/>
</ThemeContext.Provider>
);
}
}
ThemedButton.tsx:
interface ThemedButtonProps extends ThemeAwareProps {
}
interface ThemedButtonState{
}
class ThemedButton extends React.Component<ThemedButtonProps, ThemedButtonState> {
constructor(props: ThemedButtonProps) {
super(props);
}
public render() {
return (
<button className={this.props.theme}/>
)
}
}
export default withTheme(ThemedButton);
Проблема в последней строке (export default withTheme(ThemedButton)
). Компилятор TypeScript жалуется, что
Аргумент типаtypeof ThemedButton
не присваивается параметру типаnew () => Component<ThemedButtonProps, ThemedButtonState, any>
.
Чего мне не хватает?