小编dan*_*woz的帖子

要求子级在 React + Typescript 中接受 ref 属性

使用 React + Typescript,我想创建一个children仅接受单个子项的 prop,该子项接受理解并接受ref属性。基本上,我的孩子类型应该接受:

  • React 类组件的实例
  • 标准 React HTML 元素(例如<button>, <div>
  • forwardRef包装的函数组件

它不应该接受:

  • 常规函数组件
  • 文本节点,例如字符串或数字

我对这种类型的目标是使用一定程度的确定性将children引用注入到子级中,而不会被完全忽略。React.cloneElementref

我努力了

import React from "react";

type Props = {
    // EDIT: This is how I originally typed `children` to
    // get a decent compile time check that returns errors
    // if the children is a text node or multiple elements.
    // The same effect can be achieved with the `ReactElement` type. …
Run Code Online (Sandbox Code Playgroud)

typescript reactjs

5
推荐指数
1
解决办法
2711
查看次数

如何将 serde_json 与 enum 等联合类型一起使用?

我有两个结构体,我想将它们序列化/反序列化,并将标签作为"type"JSON 中的字段,如下所示。

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
struct ThingA {
    value: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
struct ThingB {
    value: usize,
}
Run Code Online (Sandbox Code Playgroud)

这些按预期序列化。例如,

let a = ThingA { value: 0 };
println!("{}", serde_json::to_string(&a)?);
// This yields the expected result:
// {"type":"ThingA","value":0}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试添加枚举来代替结构的联合类型时,我遇到了麻烦。

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
enum Thing {
    ThingA(ThingA),
    ThingB(ThingB),
}
Run Code Online (Sandbox Code Playgroud)

上面的定义对于反序列化 JSON 来说效果很好,但在序列化过程中添加了一个额外的字段。

let json = r#"{"type": "ThingB", "value": 0}"#;
let thing: Thing = serde_json::from_str(json)?;
// Correctly …
Run Code Online (Sandbox Code Playgroud)

rust serde serde-json

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

标签 统计

reactjs ×1

rust ×1

serde ×1

serde-json ×1

typescript ×1