这是高阶组件类
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;
当我访问Component
的props
时,我得到props.token
作为undefined
?有什么方法可以传递新道具吗?
如果组件有另一个名为isAuthenticated
的道具,我想您需要将token
获取到该组件。你可以像下面这样做。
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>
);
}
代码沙盒