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

React无状态/函数组件如何打印所有传入的props?

在React函数组件中打印所有Props的方法

嘿,这个问题问得好!在类组件里用this.props打印所有传入属性很直接,但函数组件的写法不一样,咱们一步步来解决:

核心思路:拿到完整的Props对象

函数组件的props是作为单个参数传入的,如果你已经像示例里那样解构了部分属性,想要查看全部props的话,得先确保你能拿到完整的props对象,具体有两种常用方式:


方式1:先接收完整props,再解构需要的属性

把你的组件参数改成先接收整个props对象,然后在内部解构你需要的属性,这样就能直接打印所有props了,包括withRouter注入的history、location、match这些:

const CollaboratorListContainer = (props) => {
  // 直接打印所有props,包括withRouter提供的
  console.log('所有传入的Props:', props);

  // 解构你需要的属性,不影响原有逻辑
  const { 
    searchTerm, 
    handleFilterChange, 
    visibleFilters, 
    setVisibleFilters, 
    deleteCollaborators, 
    companyId, 
    title 
  } = props;

  return(
    <Grid fluid>
      <MainContentHeader title={'Collaborateurs'} />
      {/* 你的组件内容 */}
    </Grid>
  );
}

// 别忘了用withRouter包裹(如果需要的话)
export default withRouter(CollaboratorListContainer);

方式2:保留解构写法,同时捕获剩余属性

如果你不想修改参数的解构写法,也可以用ES6的剩余运算符把未解构的props都存起来,然后把已解构的和剩余的合并打印(不过这种方式不如第一种直接):

const CollaboratorListContainer = ({ 
  searchTerm, 
  handleFilterChange, 
  visibleFilters, 
  setVisibleFilters, 
  deleteCollaborators, 
  companyId, 
  title,
  ...restProps // 捕获所有未解构的props,包括withRouter的
}) => {
  // 合并已解构的和剩余的,得到完整props
  const allProps = {
    searchTerm,
    handleFilterChange,
    visibleFilters,
    setVisibleFilters,
    deleteCollaborators,
    companyId,
    title,
    ...restProps
  };
  console.log('所有传入的Props:', allProps);

  return(
    <Grid fluid>
      <MainContentHeader title={'Collaborateurs'} />
      {/* 你的组件内容 */}
    </Grid>
  );
}

export default withRouter(CollaboratorListContainer);

额外小技巧:用React DevTools快速查看

其实在开发环境,你完全不用写console.log,打开React DevTools(浏览器扩展),找到你的CollaboratorListContainer组件,就能在侧边栏看到所有传入的props,包括withRouter注入的属性,非常直观!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:22:50