簡體   English   中英

在 React 中通過擴展運算符傳遞道具

[英]Passing props via spread operator in React

更新:plot 在此組件上已大大加厚,因為@wawka 深入文檔並發現這應該可以工作,但是 react-router-dom v^5.0.1 中有一些不穩定的設置。 我仍在處理它,但這看起來可能需要重寫myLink2組件。

使用 React 我有一個組件,我需要傳遞一個“id”道具來在 html 錨上呈現一個 id。 從這個錨點的最低回報水平開始,我們有:

// links.jsx
export const MyLink = ({children, location, ...props}) => {
  const href = "mydomain.com" + location;
  return (
    <a href={href} {...props}>{children}</a>
  )
}
export const MyLink2 = ({children, location, ...props}) => {
  return (
    <RouterLink to={location} {...props}>{children}</RouterLink>
  )
}

//components.jsx
export const Block = ({linkLocation, htmlId, children, externalLink: isExternalLink}) => {
  const EditLink = isExternalLink ? MyLink : MyLink2;
  return <div className="outer-div">
    <div className="inner-div">
      {children}
    </div>
 
    <EditLink location={editLocation} id={htmlId}>{translate('edit')}</EditLink>
  </div>
}

export const Summary = ({info1, info2, info3}) => {
  return <Block editLocation={'/edit/location/' + info2} htmlId={'i-am-id-' + info2}>
    <div>{info1}</div>
    <div>{info2}</div>
    <div>{info3}</div>
  </Block>
}

htmlId是我正在尋求傳遞給myLink以分配錨點的 id 屬性,但在頁面呈現時它不會出現。 是因為 id 是受保護/特殊的嗎? 我是否需要將 props 上的擴展運算符分配給EditLink組件? 我在某個地方錯過了一個通過點嗎? 我特別困惑,因為類似的問題表明傳播運算符是做我正在尋找的正確的事情。

指導將不勝感激!

根據所有研究,這應該有效。 因為它不會在我的應用程序中,所以解決方法是使用第三個MyLink3 我將其設置為准系統鏈接渲染並將組件傳遞給MyLink2

像這樣:

// links.jsx
export const MyLink = ({children, location, ...props}) => {
  const href = "mydomain.com" + location;
  return (
    <a href={href} {...props}>{children}</a>
  )
}
export const MyLink2 = ({children, location, ...props}) => {
  return (
    <RouterLink to={location} component={MyLink3} {...props}>{children}</RouterLink>
  )
}
export const MyLink3 = ({children, location, ...props}) => {
  return (
    <a href={href} {...props}>{children}</a>
  )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM