zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[React] Implement a Higher Order Component with Render Props

React with Component order render Props Implement higher
2023-09-14 09:00:51 时间

When making a reusable component, you'll find that people often like to have the API they're most familiar with, so in this lesson we'll recreate the withToggle Higher Order Component using our new ConnectedToggle render prop component.

 

function withToggle(Component) {
  function Wrapper(props, context) {
    const {innerRef, ...remainingProps} = props
    return (
      <ConnectedToggle
        render={toggle => (
          <Component
            {...remainingProps}
            toggle={toggle}
            ref={innerRef}
          />
        )}
      />
    )
  }
  Wrapper.displayName = `withToggle(${Component.displayName ||
    Component.name})`
  Wrapper.propTypes = {innerRef: PropTypes.func}
  Wrapper.WrappedComponent = Component
  return hoistNonReactStatics(Wrapper, Component)
}