queryselector

    技术2022-07-11  153

    queryselector

    Flow, the static type checker used in many React projects, feels like a gift and a curse at times; a gift in that it identifies weaknesses in your code, and a curse that sometimes you feel like you're needlessly adjusting your code to satisfy Flow.  I've grown to appreciate Flow but that doesn't mean I end up spending extra hours finding new ways to code.

    Flow是许多React项目中使用的静态类型检查器,有时感觉像是礼物和诅咒。 这是一个礼物,它可以识别代码中的弱点,还有一个诅咒,有时您会觉得自己不必要地调整代码来满足Flow的要求。 我已经对Flow产生了赞赏,但这并不意味着我最终要花费额外的时间来寻找新的编码方法。

    I recently ran into an issue where I was querying for a node in a React element and then using querySelector on that node to find a child; surprisingly Flow took issue:

    最近,我遇到了一个问题:我在React元素中查询一个节点,然后在该节点上使用querySelector查找一个子节点。 令人惊讶的是Flow出现了问题:

    Cannot call node.querySelector because property querySelector of unknown type [1] is not a function. 71│ const { maxHeight } = this.state; 72│ const node = ReactDOM.findDOMNode(this); [1] 73│ if (node && node.querySelector) { 74│ const popupNode = node.querySelector(".preview-popup"); 75│ if (popupNode) { 76│ popupNode.style.maxHeight = `${maxHeight}px`; 77│ } /private/tmp/flow/flowlib_34a4c903/react-dom.js [1] 14│ ): null | Element | Text; Found 1 error

    It turns out that findDOMNode can return type Text, and thus querySelectorAll would be undefined;  Flow doesn't like undefined.  The solution is to use instanceOf  with HTMLElement:

    事实证明findDOMNode可以返回Text类型,因此querySelectorAll将是undefined ; Flow不喜欢undefined 。 解决方案是将instanceOf与HTMLElement一起使用:

    if (node instanceOf HTMLElement) { // ... }

    The solution makes sense but a part of me silently rages that && node.querySelector doesn't qualify.  In the end, Flow is so helpful that little changes like this don't get me too wound up.

    该解决方案很有意义,但我的一部分默默地&& node.querySelector不符合条件。 最后,Flow非常有用,以至于像这样的微小变化都不会使我感到困惑。

    翻译自: https://davidwalsh.name/react-node-flow

    queryselector

    Processed: 0.010, SQL: 9