【发布时间】:2019-07-24 06:57:42
【问题描述】:
在我的代码中,我必须在不同的地方使用相同的代码行。所以我认为现在是将这段代码放入某种基类的正确时机。我已经阅读了有关Higher-Order Components 的信息,这似乎是可行的方法,并且按照一些示例,我最终得到了以下代码,但该代码不起作用。我已经尝试了一些方法,但无法让它工作。
我的 HOC:
export interface HocProps {
DynamicId: string
}
const withDiv = (hocProps) => (BaseComponent) => {
return class extend React.Component {
render() {
return (
<div id={ hocProps.DynamicId }>
<BaseComponent />
</div>
);
}
}
}
export default withDiv;
要被 div 包裹的组件:
import withDiv from './MyHoc';
class MyComponent extends React.Component {
render() {
return (
<h3>Some content here</h3>
);
}
}
export default withDiv({ DynamicId: <dynamic value> })(MyComponent);
另一个使用 MyComponent 的组件:
import MyComponent from './MyComponent';
export class OtherComponent extends React.Component {
render() {
return (
<div>
... Some content here ...
<MyComponent DynamicId={ 'id123' } />
</div>
);
}
}
我想在 OtherComponent 中传递一个 id。然后在 MyComponent 中,这个 id 必须作为 传递给 HOC,这是行不通的。我只能将静态值传递给 HOC。
我是新手,我想我犯了同样的错误。
所以我的问题是:我做错了什么以及如何做对了? 也许还有另一种/更好的方法?
提前致谢。
编辑: 我希望得到这样的结果:
<div>
... Some content here ...
<div id='id123'>
<h3>Some content here</h3>
</div>
</div>
【问题讨论】:
-
您将
OtherComponent中的动态ID 传递到哪里? -
对不起。我已经更新了代码,但我不确定这是否可行。
标签: reactjs higher-order-components