使用 React + Typescript,我想创建一个children仅接受单个子项的 prop,该子项接受理解并接受ref属性。基本上,我的孩子类型应该接受:
<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) 我有两个结构体,我想将它们序列化/反序列化,并将标签作为"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)