[英]Passing props to a React Redux connected component wrapped in HOC
我正在使用 HOC 用 Redux Provider 包裝我的所有組件。 但是當單獨使用組件時,我有時需要將道具傳遞給它們,而使用 ownProps 會從 HOC 包裝器中獲取道具。
如何將 props 直接傳遞給連接的組件?
我本質上是將 React 灑到現有站點,因此我需要使用 HTML 元素作為容器將我的組件呈現到 DOM。 我希望所有容器都連接到商店,但我也希望將數據直接傳遞給頁面上的 HTML 元素並在組件中使用該數據。
// HOC component 'withStore.js'
export default function (WrappedComponent) {
function ReduxStore() {
return (
<Provider store={ store }>
<WrappedComponent testProp="Dont show me!" />
</Provider>
);
}
return ReduxStore;
}
// The connected component I want to pass props directly to
export class ListingThumbnails extends PureComponent {
render() {
const {
ownProps,
} = this.props;
console.log(this.props.ownProps);
}
}
const mapStateToProps = (state, ownProps) => ({
state,
ownProps,
});
export default withStore(connect(mapStateToProps)(ListingThumbnails));
// Rendering to the DOM
ReactDOM.render(
<ListingThumbnailsComponent testProp="Show me!" />,
document.querySelector('#listing-thumbnails-container'),
);
控制台日志顯示傳遞給 WrappedComponent 的道具
但我希望它顯示傳遞給 ListingThumbnailsComponent 的道具
我不確定你的問題,但你的 ReduxStore 現在是一個組件。 它是圍繞“包裝組件”的一個組件。 這意味着您必須將 ReduxStore 的 props 傳遞給它的 child 以控制台日志更深層次的 props:
export default function (WrappedComponent) {
function ReduxStore(props) {
return (
<Provider store={ store }>
<WrappedComponent {...props} />
</Provider>
);
}
return ReduxStore;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.