什么是Reacts函数来检查属性是否适用?

时间:2018-06-21 21:13:00

标签: reactjs

基于此问答:

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如何进行检查?我可以重用他们的代码吗?

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:1)

用于验证属性名称的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中的属性列表复制到您的项目中,然后使用它来过滤掉此处未列出的属性。

相关问题