简体   繁体   English

将 props 传递给封装在 HOC 中的 React Redux 连接组件

[英]Passing props to a React Redux connected component wrapped in HOC

I am using a HOC to wrap all my components with the Redux Provider.我正在使用 HOC 用 Redux Provider 包装我的所有组件。 But when using the components individually I sometimes need to pass props to them and using ownProps gives me the props from the HOC wrapper.但是当单独使用组件时,我有时需要将道具传递给它们,而使用 ownProps 会从 HOC 包装器中获取道具。

How can I pass props directly to the connected component?如何将 props 直接传递给连接的组件?

I am essentially sprinkling React to an existing site, so I need to render my components to the DOM using HTML elements as containers.我本质上是将 React 洒到现有站点,因此我需要使用 HTML 元素作为容器将我的组件呈现到 DOM。 I want all the containers to be connected to the store but I also want to pass data directly to the HTML elements on the page and use that data in the component.我希望所有容器都连接到商店,但我也希望将数据直接传递给页面上的 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'),
);

The console log is displaying the props passed to the WrappedComponent控制台日志显示传递给 WrappedComponent 的道具

But I want it to show the props passed to the ListingThumbnailsComponent但我希望它显示传递给 ListingThumbnailsComponent 的道具

I'm not sure to get your problem, but your ReduxStore is a component now.我不确定你的问题,但你的 ReduxStore 现在是一个组件。 It's a component around your "wrapped component".它是围绕“包装组件”的一个组件。 It means that you have to pass the props of the ReduxStore to its child to console log the props at a deeper level:这意味着您必须将 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM