Javascript React HOC can';t将道具传递给增强组件
我有一段代码:Javascript React HOC can';t将道具传递给增强组件,javascript,reactjs,typescript,react-context,Javascript,Reactjs,Typescript,React Context,我有一段代码: const defaultValue = new Api() const ApiContext = React.createContext(defaultValue); const ApiProvider = ApiContext.Provider; const ApiConsumer = ApiContext.Consumer; const withApi = (Enhanced: any) => { return ( &l
const defaultValue = new Api()
const ApiContext = React.createContext(defaultValue);
const ApiProvider = ApiContext.Provider;
const ApiConsumer = ApiContext.Consumer;
const withApi = (Enhanced: any) => {
return (
<ApiConsumer>
{api => {
return <Enhanced api={api}/>;
}}
</ApiConsumer>
)
}
export default ApiContext;
export {ApiContext, ApiProvider, ApiConsumer, withApi};
我做错了什么?
如何将api道具传递给增强组件
[编辑]
这就是我如何调用我的组件:
App.tsx
class App extends React.Component {
render() {
return (
<React.Fragment>
<Switch>
{routes.map(({ path, exact, component: C }) => {
return <Route
key={path}
path={path}
exact={exact}
render={(props) => {
return withApi(<C {...props} />);
}} />
})}
</Switch>
</React.Fragment>
)
}
}
类应用程序扩展了React.Component{
render(){
返回(
{routes.map({path,exact,component:C})=>{
返回{
用api()返回;
}} />
})}
)
}
}
您没有正确编写withApi HOC。它应该返回一个功能组件,而不是JSX
const withApi = (Enhanced: any) => {
return (props) => {
return (
<ApiConsumer>
{api => {
return <Enhanced {...props} api={api}/>;
}}
</ApiConsumer>
)
}
}
constwithapi=(增强型:any)=>{
返回(道具)=>{
报税表(
{api=>{
返回;
}}
)
}
}
像这样使用它
class App extends React.Component {
render() {
return (
<React.Fragment>
<Switch>
{routes.map(({ path, exact, component: C }) => {
const Comp = withApi(C);
return <Route
key={path}
path={path}
exact={exact}
render={(props) => {
return <Comp {...props}/>
}} />
})}
</Switch>
</React.Fragment>
)
}
}
类应用程序扩展了React.Component{
render(){
返回(
{routes.map({path,exact,component:C})=>{
常数Comp=带API(C);
返回{
返回
}} />
})}
)
}
}
感谢您的回复。刚刚尝试了一下,我得到了这样一个错误:“警告:函数作为React子函数无效。如果您返回的是组件而不是从render返回,则可能会发生这种情况。或者您可能想调用此函数而不是返回它。”谢谢!它工作得非常好。但为什么这是错误的:withApi()?因为您在withApi函数中增强了JSX,并且仍然试图将其作为组件呈现
const withApi = (Enhanced: any) => {
return (props) => {
return (
<ApiConsumer>
{api => {
return <Enhanced {...props} api={api}/>;
}}
</ApiConsumer>
)
}
}
class App extends React.Component {
render() {
return (
<React.Fragment>
<Switch>
{routes.map(({ path, exact, component: C }) => {
const Comp = withApi(C);
return <Route
key={path}
path={path}
exact={exact}
render={(props) => {
return <Comp {...props}/>
}} />
})}
</Switch>
</React.Fragment>
)
}
}