You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件参数解构疑问:为何用<C>而非<component>?

Understanding This React Router Wrapper Component

Great question—this code uses some handy JavaScript and React features that might look confusing at first, so let’s break it down step by step.

1. Why the object parameter instead of a single props argument?

This is object destructuring assignment, a core JavaScript syntax that lets you extract specific properties directly from an object when defining a function’s parameters.

When someone uses this component, they’ll pass props like:

<CustomRoute 
  component={HomePage} 
  props={{ currentUser: user }} 
  path="/home"
/>

The destructuring ({ component: C, props: cProps, ...rest }) does three key things:

  • Takes the component prop from the input and renames it to C (shorter, and follows React’s component naming rules)
  • Takes the props prop and renames it to cProps (to avoid confusion with the route’s own built-in props)
  • Collects all other props (like path, exact, etc.) into the rest object using the spread operator (...)

Without destructuring, you’d have to write much more verbose code:

export default (props) => {
  const C = props.component;
  const cProps = props.props;
  // Manually clean up extra props for the Route component
  const rest = { ...props };
  delete rest.component;
  delete rest.props;
  
  return <Route {...rest} render={routeProps => <C {...routeProps} {...cProps} />} />;
};

2. Why use <C> instead of <component>?

React has a strict JSX rule: capitalized identifiers are treated as custom React components, while lowercase ones are interpreted as standard HTML tags.

If you tried to use <component>, React would look for an HTML <component> tag (which doesn’t exist!) and throw an error. By renaming the extracted component prop to C (a capital letter), we’re explicitly telling React: "This is a custom component, not an HTML element."

3. What’s the technical name for this pattern?

  • The parameter handling itself is called object destructuring with renaming—this is a JavaScript feature, not specific to React.
  • The component as a whole is a React Router wrapper component (or a simple Higher-Order Component, HOC). HOCs are functions that take a component and return a new component with added functionality—in this case, it simplifies passing extra props to routed components without repeating render prop logic every time.

To dive deeper, you can search for terms like:

  • "JavaScript object destructuring assignment"
  • "React JSX component naming rules"
  • "React Router custom route components"
  • "React Higher-Order Components (HOCs)"

内容的提问来源于stack exchange,提问作者LondonAppDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:40:05