如何解决React 中数据属性的通用解决方案
我的项目中有一些重复的代码,如下所示:
function MyComp({prop1,prop2,...restProps}) {
// ...
const dataAttributes = Object.keys(restProps).reduce((acc,key) => {
if (key.startsWith('data-')) {
acc[key] = restProps[key];
}
return acc;
},{});
return (
<div {...dataAttributes}>
{/* ... */}
</div>
);
}
我正在考虑自动化此行为(如果组件是 html 元素,则将以 data-
开头的 props 传递给组件的根元素)。
有什么想法吗?
解决方法
也许你可以为你使用的 html 标签创建一个自定义组件,比如 RichDiv、RichSpan...它会像:
const getDataAttributes = (inputProps = {}) => Object.keys(inputProps).reduce((acc,key) => {
if (key.startsWith('data-')) {
acc[key] = inputProps[key];
}
return acc;
},{});
function RichDiv({children,className,...restProps}) {
const dataAttributes = getDataAttributes(restProps);
return (
<div {...dataAttributes} className={className}>
{children}
</div>
);
}
function RichSpan({children,...restProps}) {
const dataAttributes = getDataAttributes(restProps);
return (
<span {...dataAttributes} className={className}>
{children}
</span>
);
}
您可以像我对 className 所做的那样将任何其他列入白名单的 prop 添加到自定义组件中,甚至可以改进您所做的 props 过滤器功能,使其返回数据属性和其他 HTML 公共属性。然后,您只需导入并使用 RichDiv 而不是 vanilla div 等。
,第一个不是很复杂的步骤可能是将减少部分提取为一个单独的效用函数,如下所示:
export function extractDataAttributes(props) {
return Object.keys(props).reduce((acc,key) => {
if (key.startsWith("data-")) {
acc[key] = props[key];
}
return acc;
},{});
}
然后您可以通过以下更短的方式使用它:
function MyComp({prop1,prop2,...restProps}) {
// ...
return (
<div {...extractDataAttributes(restProps)}>
{/* ... */}
</div>
);
}
这样做,您还将明确标记生成的标记具有 data-
属性。另一方面,不会有不必要的细节。
如果您发现此解决方案在某些时候不够用,那么使用 HOC 查看其子项并更新它们可能是个好主意。但是,这种方法可能会降低代码的明确性。
,你可以创建一个 HOC 函数,在那里你可以将剩余的 props 传递给 Component:
const withDataAttribute = (Component) => (props) => {
let passThroughProps = { ...props }
const dataAttributes = Object.keys(passThroughProps).reduce((acc,key) => {
if (key.startsWith('data-')) {
acc[key] = passThroughProps[key];
const { [key]: any,...rest } = passThroughProps
passThroughProps = rest
}
return acc;
},{});
return (
<div {...dataAttributes}>
<Component {...passThroughProps} />
</div>
);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。