简体   繁体   English

React,如何传递已知属性和props.children

[英]React, how to pass known properties and props.children

Question on how to pass properties into React methods.关于如何将属性传递给 React 方法的问题。 Probably a very easy question asked before but since I don't know how to articulate it properly, do bear with me and feel free to point me to the duplicate.之前可能是一个非常简单的问题,但由于我不知道如何正确表达它,请耐心等待并随时将我指向副本。

I'd like to use some known properties and prop.children of a React component at the same time, how do I pass them into my React methods?我想同时使用 React 组件的一些已知属性和 prop.children,如何将它们传递给我的 React 方法?

For example, I know to pass a known property into React method component we do this:例如,我知道将已知属性传递给 React 方法组件,我们这样做:

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

And the to use prop.children we need to do this:而要使用 prop.children 我们需要这样做:

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

And now I have a function that I need both prop1 and prop2 and also the props.children.现在我有一个 function 我需要 prop1 和 prop2 以及 props.children。 How should I construct the syntax to realize this need?我应该如何构造语法来实现这种需求?

ie essentially using it as:即本质上将其用作:

<SomeComponent prop1={value1} prop2={value2}>
   <NestedComponent />
</SomeComponent>
const MyComp = props => {
  const {prop1, children} = props;
  // do something with props
  // do something with prop1
  // do something with children
  return (<div>{children}</div>);
}

The ({prop1, prop2}) syntax is a destructuring assignment introduced in ES6. ({prop1, prop2})语法是 ES6 中引入的解构赋值。 Actually what the function get is an object containing keys prop1 , prop2 , like this实际上 function 得到的是一个 object 包含键prop1prop2 ,像这样

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

You can read this for more detail: Unpacking fields from objects passed as a function parameter .您可以阅读此内容以了解更多详细信息: 从作为 function 参数传递的对象中解包字段

Hence, when passing both prop1, prop2, and children, you can use either syntax below:因此,当同时传递 prop1、prop2 和 children 时,您可以使用以下任一语法:

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

you can do something like this -你可以做这样的事情 -

<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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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