简体   繁体   中英

Passing props via spread operator in React

Update: The plot has greatly thickened on this component as @wawka dove deep into the documentation and found that this should work but there are some wonky setups within the react-router-dom v^5.0.1. I'm still working through it but, this looks like it might require a rewrite of the myLink2 component.

Using React I have a component that I need to pass an 'id' prop to render an id on the html anchor. Starting at the lowest return level for this anchor point and working up we have:

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

That htmlId is what I'm seeking to pass up to myLink to assign the anchor's id attribute yet on page render it doesn't appear. Is it because id's are protected/special? Do I need to assign the spread operator on props to the EditLink component? Am I missing a passing point somewhere? I'm especially confused because similar questions show the spread operator as being just the right thing to do what I'm seeking.

Guidance would be much appreciated!

By all the research, this should have worked. As it would not in my application the workaround was to use a third MyLink3 . I set it to a barebones link render and pass the component to MyLink2 .

Like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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