小编ent*_*ull的帖子

将React组件注入HTML

我试图从外部来源接收一段HTML标记,并将React组件注入到它的特定部分中,然后再进行渲染。

为此,我一直在使用react-html-parserhttps://github.com/wrakky/react-html-parser

我有这个示例在工作……尽管如此,但它感觉很笨拙,不可能实现这一目标的最佳方法。

// a simple component
const Image = props => {
    return <img {...props}/>    
};

// this resource comes from an external source and can differ
// ultimately, I would like to be able to target certain elements selecting their data-attributes
// to insert a React component
const externalHTML = '<div class="image"></div>';

// using the react-html-parser library to convert the externalHTML into a React component
const DynamicReactComponent = ReactHtmlParser(externalHTML);

// manually injecting a React …
Run Code Online (Sandbox Code Playgroud)

reactjs

8
推荐指数
1
解决办法
413
查看次数

带有 React-Navigation 的类型安全 navigationHandler

我的 React Native 应用程序的 Typescript 和 React Navigation 存在问题。我的项目中有以下设置,这在使用例如时为我提供了很棒的帮助和自动完成功能navigation.push()

类型

import { StackNavigationProp } from '@react-navigation/stack';

export type RootStackParamList = {
    Home: undefined;
    Content: undefined;
    List: undefined;
};

export type StackNavigationProps = StackNavigationProp<RootStackParamList>;
Run Code Online (Sandbox Code Playgroud)

用法

const navigation = useNavigation<StackNavigationProps>();
Run Code Online (Sandbox Code Playgroud)

但是,我创建了一个导航处理程序函数,该函数接受一个被馈送到navigation.push. 只要参数的类型是 type ,它就可以正常工作any

const navigationHandler = useCallback((targetScreen) => {
    navigation.push(targetScreen);
}, [navigation]);
Run Code Online (Sandbox Code Playgroud)

但我对这种类型并不满意,any并且希望它targetScreen实际上只是我在其中声明的屏幕之一RootStackParamList类型中声明的屏幕之一。我尝试了无数种方法来满足push导航对象的方法,但我被困住了。

以下尝试是最成功的,但尚未完全发挥应有的作用。它确实让我在可用屏幕上自动完成,但是push仍然不满意。

类型:

export type NavigationScreen<T extends RootStackParamList> = {
    [K in keyof …
Run Code Online (Sandbox Code Playgroud)

typescript react-native react-navigation

3
推荐指数
1
解决办法
4877
查看次数

具有动态和静态属性的接口

我有一个关于更动态的接口的问题,其中动态和静态属性可以一起使用 - 即使它们是不同的类型。这可能吗?如果是的话,这还有什么意义吗?

假设我想要这样的东西。

type MyCustomType = {
    foo: string;
};

export interface MyInterface {
    [key: string]: MyCustomType;
    bar: string;
};
Run Code Online (Sandbox Code Playgroud)

我想确保某个 prop (我事先不知道其名称)指向 type 的值MyCustomType。我确实知道其中的其余属性MyInterface的名称,并且它们指向其他类型。

上面的代码会导致以下错误:

Property 'bar' of type 'string' is not assignable to string index type MyCustomType.
Run Code Online (Sandbox Code Playgroud)

我可以通过使用交集(如下例所示)来解决这个问题,或者any 但是..这也会影响我的动态道具并破坏其类型的保证。

export interface MyInterface {
    [key: string]: MyCustomType | string;
    bar: string;
};
Run Code Online (Sandbox Code Playgroud)

非常感谢任何建议:)

typescript

2
推荐指数
1
解决办法
446
查看次数