如何根据关键字有条件地更改按钮的颜色



我希望在每张卡的顶部显示带有引导徽章的卡。我想根据宠物的状态有条件地更改徽章的颜色。

render() {
        const isAdmin = true;
        const post = this.props.post; 
        const id = this.props.post.post_ID; 
        console.log(post);

     return (
        <div>
        <Card id="card-main" style={{ width: '18rem', margin: '12px' }}>
        <span class="badge badge-secondary">{post.petStatus}</span>
            <Card.Img id="card-img-top" variant="top" src={post.img_path} />
            <Card.Body>
                <Card.Title>{post.pet_name}</Card.Title>
                <Card.Text id="PetName">
                  <strong>{post.petName} </strong>
                </Card.Text>
                <Card.Text id="content">
                  {post.content} 
                </Card.Text>
                <Card.Text>
                  <strong>Posted By: </strong>{post.name}
                </Card.Text>
                <Card.Text
                  <strong>Posted: </strong>{post.postedOn}
                </Card.Text>
          </Card>

根据您需要的颜色数量,您可以内联:

    <Card id="card-main" style={{ width: '18rem', margin: '12px' }}>
    <span class="badge badge-secondary" style={{color: post.petStatus === "adopted" ? "blue" : "red"}}>{post.petStatus}</span>

。或者,如果您需要多种颜色,最好编写一个根据状态返回样式的帮助程序:

getStyleForStatus = (status)=>{
    let statusColor
    switch (status){
        case "adopted":
            statusColor = "blue"
            break;
        case "lost":
            statusColor = "red"
            break;
        default:
          //
      return {color:statusColor}
    }
}
 render() {
    const isAdmin = true;
    const post = this.props.post; 
    const id = this.props.post.post_ID; 
    console.log(post);

 return (
    <div>
    <Card id="card-main" style={{ width: '18rem', margin: '12px' }}>
    <span class="badge badge-secondary" style={getStyleForStatus(post.petStatus)}>{post.petStatus}</span>
          {/* ... */}
      </Card>

最新更新