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

Making each props title a different color

我使用 props:

在 React 中编写了个人资料卡片
const Profilebox = props => (
<div className="Profilebox">
    <img src={props.image} />
    <h1>{props.title}</h1>
    <h2>{props.subtitle}</h2>
    <p>{props.text}</p>
</div>)

是否可以为每张卡片使用不同的 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>)

你可以把风格写在道具上。或者你可以纠正一个函数,它会随机 select 一种颜色并以此方式设置颜色。

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

绝对有可能将不同的颜色从其父级传递给 Card。假设您正在通过道具进行映射以将适当的数据分配给每张卡片,您将能够添加另一个道具。在父级中,有些愚蠢的东西:

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

然后,在您的个人资料框中,您将执行快速内联样式:

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 => (
<div className="Profilebox">
    <img src={props.image || null} />
    <h1>{props.title || 'default Title'}</h1>
    
    <h2 className={`bg_${Math.floor(Math.random() * Math.floor(3))+1}`}>{props.subtitle || 'default subtitle'}</h2>
    <p>{props.text || 'default Text'}</p>
</div>)

const Profiles = () => (<div><Profilebox image = ''/><Profilebox  image = ''/></div>)

ReactDOM.render(<Profiles/>, document.querySelector("#app"))
.Profilebox {
border : 1px solid gray;
width:50%;
}

.bg_1{
  color:green;
}
.bg_2{
  color:red;
}
.bg_3{
  color:yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app">
  
</div>