[英]How to get only specific elements from array by comparing them in javascript?
[英]How to get specific elements from an object to use them as props for a component
有一個接受一些道具的組件:
<MyComponent first="first" second="second" third="third" />
我們可以創建一個 object:
const mockData = {
first: 'test1',
second: 'test2',
third: 'test3'
};
並通過以下方式將其用作道具: <MyComponent {...mockData} />
並且它工作正常。
我想要的是僅使用mockData
object 中的前兩個元素,因為它們都不是必需/強制的,所以應該不是問題。
所以我試過這樣: <MyComponent {...mockData.first, ...mockData.second} />
但它不起作用。
當然它可以寫成<MyComponent first={mockData.first} second={mockData.second} />
但這只是一個包含很少元素的示例,因為我真正的問題有更多元素。
有沒有辦法做到這一點?
您必須創建一個派生的模擬數據類型,例如:
type MyComponentType = Pick<mockdata, "first">
您可以使用 object 傳播語法:
const {third, ...rest} = mockData;
// now the variable rest has all the properties from mockData except third
<MyComponent {...rest}/>
既然你說你有更多的屬性,你可以通過在解構之前簡單地包含它們來提取你想要的任意數量的屬性,例如:
const {third, fourth, fifth, /* etc */ ...rest} = mockData;
const mockData = {
first: 'test1',
second: 'test2',
third: 'test3'
};
<MyComponent props={ mockData } />
const MyComponent = ({first, second, third}) => {
return (
<div>
first = {first}
second = {second}
third = {third}
</div>
)};
這應該適合你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.