简体   繁体   English

可重用的React组件时间表

[英]reusable react component timeline

I am building a timeline component which currently is used for measuring a day (24 hrs). 我正在构建一个时间轴组件,该组件当前用于测量一天(24小时)。 I have the intention to use it as a "global" timeline, being used to measure 24 hrs, 7 weeks or 12 months. 我打算将其用作“全局”时间轴,用于测量24小时,7周或12个月。

Here is what I have 这是我所拥有的

bullets(number) {
  const points = [...Array(number)].map((_, i) => {
    return (
      <li key={i} data-pop={i < 13 ? i + ' AM' : i-12 + " PM"}></li>
    )
  })
  return points;
}

render() {
  return (
    <Time>
      <ul>
        {this.bullets(24)}
      </ul>
    </Time>
  )
}

and I have the following result passing 24 or 7 in my function 我在函数中传递24或7得到以下结果

时间线

My doubt is how to change the "data-pop" (which is the legend of each bullet when hovered), depending on the value I pass on my function (7, 12 or 24). 我的疑问是如何根据我传递给函数的值(7、12或24)更改“数据弹出”(悬停时每个子弹的图例)。 How can I do that ? 我怎样才能做到这一点 ?

I wouldn't alter the legend based on the value, as it makes no semantic sense. 我不会根据值更改图例,因为它没有语义。 There are a couple of options that might work for you. 有几个选项可能对您有用。 One would be to have props for the number of bullets, and another for how to generate the text from those numbers. 一种是为子弹的数量提供道具,另一种为如何从这些数字生成文本的道具。 For example: 例如:

const TimeLine = ({ totalBullets, legendFunc }) => (
  <Time>
    <ul>
      {[...Array(number)].map((_, i) => (
        <li key={i} data-pop={legendFunc(i)}></li>
      ))}
    </ul>
  </Time>
)

// use like this
<TimeLine 
  totalBullets={24} 
  legendFunc={i => (i < 13) 
    ? i + ' AM' 
    : i-12 + ' PM'
  }
/>

A better way though, is to make your component completely data driven. 但是,更好的方法是使组件完全由数据驱动。 In your case this could simply be an array of text representation, but it would probably make sense to be an array of objects, so that you could have different keys for things, should the need arise. 在您的情况下,这可能只是一个文本表示形式的数组,但是将其作为对象数组可能很有意义,以便在需要时可以为事物使用不同的键。 For example, start by defining the data you want to display: 例如,首先定义要显示的数据:

// generate your bullet data somewhere
const data = [...Array(number)].map((_, i) => ({
  legend: i < 13 ? i + ' AM' : i-12 + ' PM'
}))

const TimeLine = ({ bulletData }) => (
  <Time>
    <ul>
      {bulletData.map((bullet, i) => (
         <li key={i} data-pop={bullet.legend}></li>
      ))}
    </ul>
  </Time>
)

// use like
<TimeLine bulletData={data}/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM