我有一個這樣的臨時組件:
export const withAttrs = (WrappedComponent) => {
const ModifiedComponent = (props) => (
<WrappedComponent {...props} data-test-id="this-is-a-element" />
);
return ModifiedComponent;
};
export default withAttrs;
我像這樣使用它:
import React from 'react';
import withAttrs from './withAttrs';
const SomeLink = () => <a><p>hey</p</a>;
export default withAttrs(SomeLink);
我希望有一個這樣的錨標簽:
<a data-test-id="this-is-a-element"><p>hey</p></a>
但hoc不會將 the 添加data-attribute到第一個元素。有沒有辦法做到這一點?
uj5u.com熱心網友回復:
但是 hoc 不會將資料屬性添加到第一個元素。
不是 HOC 沒有添加它,而是SomeLink,它對 HOC 傳遞給它的 props 沒有任何作用。
簡單的答案是更新SomeLink:
const SomeLink = (props) => <a {...props}><p>hey</p></a>;
到目前為止,這是比以下更好的事情。
如果你做不到,你可以讓你的 HOC 在事后添加屬性,但是讓 HOC 到達組件內部并改變東西似乎是不合適的。事實上,React 使得它創建的元素物件是不可變的,這強烈建議你不應該試圖弄亂它們。
不過,有可能,這可能只是一個壞主意:
export const withAttrs = (WrappedComponent) => {
const ModifiedComponent = (props) => {
// Note we're *calling* the function, not just putting it in
// a React element via JSX; we're using it as a subroutine of
// this component rather than as its own component.
// This will only work with function components. (You could
// write a version that handles class components as well,
// but offhand I don't think you can make one HOC that handles
// both in this case.)
const result = WrappedComponent(props);
return {
...result,
props: {
...result.props,
"data-test-id": "this-is-a-element",
},
};
};
return ModifiedComponent;
};
顯示代碼片段
/*export*/ const withAttrs = (WrappedComponent) => {
const ModifiedComponent = (props) => {
// Note we're *calling* the function, not just putting it in
// a React element via JSX; we're using it as a subroutine of
// this component rather than as its own component.
// This will only work with function components. (You could
// write a version that handles class components as well,
// but offhand I don't think you can make one HOC that handles
// both in this case.)
const result = WrappedComponent(props);
// THIS IS PROBABLY A VERY BAD IDEA. React makes these objects
// immutable, probably for a reason. We shouldn't be mucking
// with them.
return {
...result,
props: {
...result.props,
"data-test-id": "this-is-a-element",
},
};
};
return ModifiedComponent;
};
const SomeLink = () => <a><p>hey</p></a>;
const SomeLinkWrapped = withAttrs(SomeLink);
const Example = () => {
return <div>
<div>Unwrapped:</div>
<SomeLink />
<div>Wrapped:</div>
<SomeLinkWrapped />
</div>;
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Example />);
/* So we can see that it was applied */
[data-test-id=this-is-a-element] {
color: green;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
再說一次,我不認為我會這樣做,除非作為最后的手段,如果它在未來版本的 React 中出現故障,我不會感到驚訝。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/481419.html
標籤:javascript 反应 自定义数据属性 高阶组件 特设的
