简体   繁体   中英

React.Js/Typescript: How can I pass colors through props?

I'm new to React and I'm working with a component where colors where previously hard-coded. I want to be able to pass a color through props instead.

I'm also using styledComponents for the styling, if that makes any difference.

      &[checkedcolor] {
    /*&[checkedcolor="orange"] {*/
      &:checked {
        + .lbl {
          border-color: ${props => props.theme.borderColor};
          color: ${props => props.theme.color};
        }
      }
    }
  }
  &[uncheckedcolor] {
    /*&[uncheckedcolor="lightgray"] {*/
      + .lbl {
        color: ${props => props.theme.color};
      }
    }
  }
}

} `;

This is the part of the styling where I want to pass in a prop. I'm not sure if I'm doing this right.. Also "theme" is pulled from a themes.ts file which should be passed by a theme provider from a different file. The commented out portion is where the style was previously hard-coded.

  render() {
var { className, type, radioClasses, label, ...other } = this.props;
return (
  <RadioWrapper className={"radio-switch-item-wrapper " + radioClasses}>
    <input type="radio" className="ace radio-switch-item" {...other} />
    <span className="lbl">{" " + this.props.label}</span>
  </RadioWrapper>

);

} }

Here is the render.. I'm not exactly sure what is going on here. Radiowrapper is the name of the styling. Also, I'm working on someone else's code which is why I'm not totally clear on what is going on.

Your style file would look like this

const RadioWrapper = styled.div`
  ... otherstyles
  color: ${props => props.color}
`

The component file would look like this

render() {
  return(
   <RadioWrapper color="#FFFFFF"/> 
  );
}

You can pass the color in the component porps as,

<RadioWrapper fontColor="#AAAAAA"/>

then receive in styled components with props and type as,

const RadioWrapper = styled.div`
color: ${(props:{fontColor:string}) => props.fontColor}`;

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