您需要解开选项变体,我们可以通过开关来做到这一点,并使用内置的 None/Some 变体。
您可以在此处找到有关选项变体的一些文档:https ://reasonml.github.io/docs/en/newcomer-examples.html#using-the-option-type
以下是有关选项的更多文档:https ://reasonml.github.io/docs/en/variant.html#option
为此,您可以将代码更改为以下内容:
let parent = document |> Document.querySelector(".parent");
let child = switch (parent) {
| Some(p) => switch (Element.querySelector(".child", p)) {
| Some(c) => c
| None => raise(Failure("Unable to find child selector"))
}
| None => raise(Failure("Unable to find parent selector"))
};
如果您想改为登录到控制台而不是失败,则需要返回一个 valid Dom.element.t
,可能是这样的:
let emptyEl = document |> Document.createElement("noscript");
let parent = document |> Document.querySelector(".parent");
let child = switch (parent) {
| Some(p) => switch (Element.querySelector(".child", p)) {
| Some(c) => c
| None => {
Js.log("Unable to find child selector");
emptyEl;
}
}
| None => {
Js.log("Unable to find parent selector");
emptyEl;
}
};
然后,您会想要检查您的子元素是否是 anoscript
以查看您是否找到了您正在寻找的子元素。