我有一個可以轉換其他功能的功能:
//library:
let transform = function(OriginalComponent) {
let WrappedComponent (props) => {
//some transformation
return <OriginalComponent {...props} />
};
//I specifically need the original component to have a NON EMPTY name here
Object.defineProperty(WrappedComponent, "name", { value: OriginalComponent.name });
}
我目前在這樣的檔案中使用它
export const MyWrappedComponent = transform(function MyComponent(props){
return <h1>Hello {props.name}!</h1>;
});
使用此設定,我目前需要為匯出和函式使用不同的名稱。
我的問題是:我可以以某種方式將其匯出為一行,只使用一個名稱而不是兩個名稱嗎?
我試過了:
export function transform(function MyComponent(props){
return <h1>Hello {props.name}!</h1>;
});
但這是無效的,因為出口沒有名稱。
我也想過
export const MyComponent = transform((props) => {
return <h1>Hello {props.name}!</h1>;
});
但隨后transform()收到一個未命名的組件(它不知道我相信的匯出名稱?)
這是關于圖書館的標準,所以我想盡可能地保持這個例子干凈。命名一個函式然后命名匯出可能會讓人感到困惑。如果我必須命名兩者,我寧愿使用相同的名稱,但我不知道如何。
uj5u.com熱心網友回復:
如果您想使用命名匯出,并且想將函式直接傳遞給transform,則無法(合理地1)繞過重復名稱,如下所示:
export const MyComponent = transform(function MyComponent(props){
return <h1>Hello {props.name}!</h1>;
});
使用此設定,我目前需要為匯出和函式使用不同的名稱。
謝天謝地,你沒有;如上所述,在那里使用相同的名稱是完全有效的。
對于它的價值,transform我注意到該功能存在一些問題:
您不能直接寫入
name函式的屬性,它是只讀的。但是您可以通過Object.defineProperty.它沒有回傳包裝的組件。
這是一個固定的版本:
export let transform = function (OriginalComponent) {
let WrappedComponent = (props) => {
//some transformation
return <OriginalComponent {...props} />;
};
// I specifically need the original component to have a NON EMPTY name here
Object.defineProperty(WrappedComponent, "name", {
value: OriginalComponent.name,
writable: false, // This is the default, but I'm including it
// here for emphasis
configurable: true, // You definitely want to set this to `true`
enumerable: false, // (Also the default)
});
return WrappedComponent;
};
作為替代方案,您可以將展開的組件放入物件中:
export const components = {
MyComponent(props) {
return <h1>Hello ${props.name}!</h1>;
},
// ...
};
...然后對它們進行后處理:
for (const [name, component] of Object.entries(components)) {
components[name] = transform(component);
}
但這意味著您的匯出是components物件,而不是單個組件,因此您最終會得到這樣的用法:
import { components } from "./somewhere";
const { MyComponent } = components;
// ...
...這不太理想。(遺憾的是,您不能直接解構匯入。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/516220.html
上一篇:錯誤TS5083:無法讀取檔案“/tsconfig.json”
下一篇:將檔案從React/TypeScript傳遞到C#API會導致錯誤:“無法將JSON值轉換為System.Byte[]”
