Reactjs 使每个道具标题具有不同的颜色

Reactjs 使每个道具标题具有不同的颜色,reactjs,components,react-props,Reactjs,Components,React Props,我在React中使用道具对个人资料卡进行了编码: 是否可以为每张卡使用不同的h2颜色 const Profilebox = props => ( <div className="Profilebox"> <img src={props.image} /> <h1>{props.title}</h1> <h2 style={props.style}>{props.subtitle}<

我在React中使用道具对个人资料卡进行了编码:

是否可以为每张卡使用不同的h2颜色

 const Profilebox = props => (
   <div className="Profilebox">
      <img src={props.image} />
      <h1>{props.title}</h1>
      <h2 style={props.style}>{props.subtitle}</h2>
      <p>{props.text}</p>
   </div>)
你可以在道具上保留这种风格。或者,您可以修改一个函数,该函数将随机选择一种颜色,并以此方式设置颜色

 randomColorStyle = () => {

     return{color: '#' + Math.floor(Math.random()*16777215).toString(16);}
 }

 const Profilebox = props => (
   <div className="Profilebox">
      <img src={props.image} />
      <h1>{props.title}</h1>
      <h2 style={this.randomColorStyle}>{props.subtitle}</h2>
      <p>{props.text}</p>
   </div>)

绝对有可能将不同的颜色从其父级传递给卡。假设你正在通过道具进行映射,为每张卡分配适当的数据,你就可以添加另一个道具。在家长中,有些愚蠢的事情,比如:

const colorArray = ["red", "green", "blue", "orange", "black", "purple"];
profileCardData.map(profileCard => {
  let color = colorArray[Math.floor(Math.random() * colorArray.length)];
  return (
    <Profilebox image={image} text={text} style={color} subtitle={subtitle}/>
  )
然后,在Profilebox中,您可以执行快速内联样式:

const Profilebox = props => (
<div className="Profilebox">
    <img src={props.image} />
    <h1>{props.title}</h1>
    <h2 style={props.style}>{props.subtitle}</h2>
    <p>{props.text}</p>
</div>)

以其他方式分配不同的颜色会非常容易。这只是其中之一。

希望下面的代码片段能有所帮助

const Profilebox=props=> {props.title | |“默认标题”} {props.subtitle | |'默认字幕'} {props.text | |“默认文本”}

常量配置文件==> ReactDOM.render、document.querySelectorapp .档案盒{ 边框:1px纯色灰色; 宽度:50%; } .bg_1{ 颜色:绿色; } .bg_2{ 颜色:红色; } .bg_3{ 颜色:黄色; }
const Profilebox = props => (
<div className="Profilebox">
    <img src={props.image} />
    <h1>{props.title}</h1>
    <h2 style={props.style}>{props.subtitle}</h2>
    <p>{props.text}</p>
</div>)