【问题标题】:What is Reacts function for checking if a property applies?什么是用于检查属性是否适用的 Reacts 函数?
【发布时间】:2018-12-01 07:35:34
【问题描述】:

基于此问答:

React wrapper: React does not recognize the `staticContext` prop on a DOM element

答案对我的场景来说不是很好,我有很多道具,真的不喜欢复制粘贴,希望下次接触代码的人都能更新。

所以,我认为可能可行的只是重新利用 React 用来检查属性是否适合在提交之前有条件地删除属性的任何功能。

类似这样的:

import { imaginaryIsDomAttributeFn } from "react"
...

render() {
    const tooManyProps = this.props;
    const justTheRightProps = {} as any;
    Object.keys(tooManyProps).forEach((key) => {
        if (imaginaryIsDomAttributeFn(key) === false) { return; }
        justTheRightProps[key] = tooManyProps[key];
    });
    return <div {...justTheRightProps} />
}

我在 Reacts index.t.ts 中找到了 DOMAttributes 和 HTMLAttributes,并且可能将它们变成大量字符串来检查键,但是...我宁愿将其作为最后的手段。

那么,React 是如何进行检查的呢?我可以重复使用他们的代码吗?

【问题讨论】:

标签: reactjs


【解决方案1】:

以下内容并不意味着是一个完整的答案,但如果我忘记回到这篇文章,它会对你有所帮助。到目前为止,以下代码正在运行。

// reacts special properties
const SPECIAL_PROPS = [
    "key",
    "children",
    "dangerouslySetInnerHTML",
];

// test if the property exists on a div in either given case, or lower case
// eg (onClick vs onclick)
const testDiv = document.createElement("div");
function isDomElementProp(propName: string) {
    return (propName in testDiv) || (propName.toLowerCase() in testDiv) || SPECIAL_PROPS.includes(propName);
}

【讨论】:

    【解决方案2】:

    用于验证属性名称的 React 内部函数位于此处:https://github.com/facebook/react/blob/master/packages/react-dom/src/shared/ReactDOMUnknownPropertyHook.js

    它检查属性的主要内容是此处的“possibleStandardNames”属性列表:https://github.com/facebook/react/blob/master/packages/react-dom/src/shared/possibleStandardNames.js

    因此,要重用他们的代码,您可以将possibleStandardNames.js 中的属性列表复制到您的项目中,然后使用它来过滤掉未在其中列出的属性。

    【讨论】:

      猜你喜欢
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 2014-12-12
      • 2014-05-16
      • 2023-03-22
      • 1970-01-01
      • 2012-05-06
      相关资源
      最近更新 更多