[英]React, how to pass known properties and props.children
關於如何將屬性傳遞給 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}... }
現在我有一個 function 我需要 prop1 和 prop2 以及 props.children。 我應該如何構造語法來實現這種需求?
即本質上將其用作:
<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>);
}
({prop1, prop2})
語法是 ES6 中引入的解構賦值。 實際上 function 得到的是一個 object 包含鍵prop1
, prop2
,像這樣
{
prop1: ...,
prop2: ...,
...,
}
您可以閱讀此內容以了解更多詳細信息: 從作為 function 參數傳遞的對象中解包字段。
因此,當同時傳遞 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 }
你可以做這樣的事情 -
<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.