【问题标题】:React, how to pass known properties and props.childrenReact,如何传递已知属性和props.children
【发布时间】:2021-05-05 03:54:23
【问题描述】:

关于如何将属性传递给 React 方法的问题。以前可能是一个非常简单的问题,但由于我不知道如何正确表达它,请耐心等待并随时指出我的重复。

我想同时使用 React 组件的一些已知属性和 prop.children,如何将它们传递给我的 React 方法?

例如,我知道将一个已知属性传递给 React 方法组件,我们这样做:

export const SomeComponent = ({prop1, prop2}) =>{ ... do something with prop1 and prop2 }

而要使用 prop.children 我们需要这样做:

export const SomeComponent = (props) =>{ ... then some tags wrapping {props.children}... }

现在我有了一个需要 prop1 和 prop2 以及 props.children 的函数。我应该如何构造语法来实现这个需求?

即基本上将其用作:

<SomeComponent prop1={value1} prop2={value2}>
   <NestedComponent />
</SomeComponent>

【问题讨论】:

标签: javascript reactjs frontend


【解决方案1】:
const MyComp = props => {
  const {prop1, children} = props;
  // do something with props
  // do something with prop1
  // do something with children
  return (<div>{children}</div>);
}

【讨论】:

    【解决方案2】:

    你可以这样做 -

    <SomeComponent  prop1={} prop2={}>
      <div> test </div>
    </SomeComponent>
    
     export const SomeComponent = (props) =>{ ...access the prop1 as props.prop1 and prop2 
     as props.prop2 and children like props.children }
    

    【讨论】:

      【解决方案3】:

      ({prop1, prop2}) 语法是 ES6 中引入的解构赋值。 其实这个函数得到的是一个包含键prop1prop2的对象,像这样

      {
        prop1: ...,
        prop2: ...,
        ...,
      }
      

      您可以阅读本文了解更多详情:Unpacking fields from objects passed as a function parameter

      因此,当同时传递 prop1、prop2 和 children 时,您可以使用以下任一语法:

      • 使用解构赋值:
        export const SomeComponent = ({prop1, prop2, children}) => {
          ... do something with prop1, prop2, and children 
        }
        
      • 没有解构赋值:
        export const SomeComponent = (props) => {
          ... do something with props.prop1, props.prop2, and props.children 
        }
        

      【讨论】:

        猜你喜欢
        • 2021-08-04
        • 1970-01-01
        • 2020-05-27
        • 1970-01-01
        • 1970-01-01
        • 2017-11-03
        • 2021-12-13
        • 2021-03-16
        • 1970-01-01
        相关资源
        最近更新 更多