【问题标题】:How can I apply css style in props in React?如何在 React 的道具中应用 css 样式?
【发布时间】:2018-06-21 07:21:20
【问题描述】:

在此代码中,{index} 是一个列表编号,我想仅应用 1 到 3 之间的 {index} 的样式值。我是编码初学者,您能帮帮我吗?谢谢。

 _renderRankings=()=>{
  const movies= this.state.movies.map((movie, i)=>{
    console.log(movie)
      return  <L_Ranking
      title={movie.title_english}
      key={movie.id}
      genres={movie.genres}
      index={i}
      />
  })
  return movies
}

function L_Ranking({title, genres, index}){
  return (
    <div className="L_Ranking">
      <span className="L_Ranking_Number"> {index+1}</span>
      <span className="L_Ranking__Column">
        {title}
      </span>
    </div>
  )
}

【问题讨论】:

    标签: javascript jquery css reactjs


    【解决方案1】:

    如果索引在您想要的范围内,您可以创建一个空的 style 对象并添加您的样式:

    function L_Ranking({title, genres, index}){
      const style = {};
    
      if (index >= 1 && index <= 3) {
        style.backgroundColor = 'red';
      }
    
      return (
         <div className="L_Ranking" style={style}>
           <span className="L_Ranking_Number">{index+1}</span>
           <span className="L_Ranking__Column">
           {title}
           </span>
         </div>
       )
    }
    

    【讨论】:

      【解决方案2】:

      您可以有条件地渲染类样式 -

      <span className={index >= 1 && index <= 3 ? 'L_Ranking_Number' : '' } >
      

      L_Ranking_Number 仅在index 包含1-3 时应用。

      【讨论】:

        【解决方案3】:

        谢天谢地,您实际上不需要使用 JavaScript 在此处有条件地应用 css,而是可以在父类上使用 css nth-child 选择器。

        nth-child 选择器采用一个公式来决定将其样式应用于哪些子级。例如,对于以这种方式构造的 HTML,将 css 应用于从第二个孩子向上的每个孩子:

        <div className="parent-class">
            <div />
            <div />
            <div />
        </div
        

        你可以使用这个 css

        .parent-class:nth-child(n + 2) {
            background-color: papayawhip;
        }
        

        对于需要范围的情况,您可以类似地在父类上使用此 css

        .parent-class:nth-child(n + 2):nth-child(-n + 4) {
            // your css
        }
        

        Here 是您阅读有关第 n 个子选择器的好网站。

        【讨论】:

          猜你喜欢
          • 2019-09-06
          • 2020-06-11
          • 2019-03-03
          • 2020-01-24
          • 1970-01-01
          • 1970-01-01
          • 2020-06-08
          • 2022-10-20
          • 2020-11-14
          相关资源
          最近更新 更多