這是高階組件類
token是prop我想包括的
import React from "react";
export function requireAuthentication(Component) {
return class AuthenticatedComponent extends React.Component {
isAuthenticated() {
return this.props.isAuthenticated;
}
render() {;
return (
<div>
{ this.isAuthenticated === true ? <Component token={token} {...this.props} /> }
</div>
);
}
};
}
export default requireAuthentication;
當我訪問props的Component,我得到props.token的undefined?有沒有辦法傳遞新的道具?
uj5u.com熱心網友回復:
我想token如果組件有另一個名為isAuthenticated. 你可以像下面那樣做。
import React from "react";
export function requireAuthentication(Component) {
return class AuthenticatedComponent extends React.Component {
isAuthenticated() {
return this.props.isAuthenticated;
}
render() {
return (
<div>
{this.props.isAuthenticated === true ? (
<Component
token={"this_token_is_retrieved_by_requireAuthentication"}
{...this.props}
/>
) : (
<Component {...this.props} />
)}
</div>
);
}
};
}
const MyComp = requireAuthentication(({ token }) => {
return <div>token: {token}</div>;
});
export default function App() {
return (
<div className="App">
<MyComp isAuthenticated={true} />
<MyComp isAuthenticated={false} />
</div>
);
}
代碼沙箱
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/402036.html
標籤:javascript 反应 高阶组件
上一篇:當我使用javascript連接到我的RESTAPI時:跨域網路錯誤
下一篇:更改按鈕的id導致點擊事件觸發
