尝试在同一个反应组件中加载多个 C3 图表

Trying to load multiple C3 charts in same react component

我正在尝试映射数组并让图表与每个元素一起显示,但它似乎不起作用。同样的代码出现一次正确,但没有其他时间,我不确定我错过了什么。

我试图将 id 名称更改为它标记图表的位置,我通过添加索引变量来做到这一点,但仍然无法正常工作

import React from 'react'
import c3 from '/c3.min.js'

class SearchedFood extends React.Component {
  constructor(props) {
    super(props)
    this.state = {

    }
    this.graph = this.graph.bind(this)
  }


  graph(index) {
    c3.generate({
        bindto: '#class' + index,
        data: {
        columns: [
            [1, 2, 3], [2, 3,4]
        ],
        type: 'bar'
        },
        bar: {
            width: {
                ratio: 0.3
            }
        }
   })}


  render () {
    return (
      <div>
        {this.props.foodResults.map((food, i) => {
          return (
            <div key={i}>
             <label>{food.recipe.label}</label>
             <img className="card-img-top" src={food.recipe.image} height="250" width="auto"></img>
             <a href={food.recipe.url}>{food.recipe.source}</a>
             <p>{food.recipe.dietLabels[0]}</p>

             <div>
              {food.recipe.ingredientLines.map((ingredient, i) => {
                return (
                  <p key={i}>{ingredient}</p>
                ) 
              })}
            </div>

            <p>Calories {Math.floor(food.recipe.calories/food.recipe.yield)}</p>


            <div id={`class${i}`}>{this.graph(i)}</div>


          </div>
        )
      })}

    </div>
    )
  }
}

export default SearchedFood

bindto: '#class' + index,/{this.graph...} 行不通。 React 不会将 directly/immediately 渲染到 DOM.

看起来你可以使用带有 bindTo 的元素 - 你最好的选择是使用 ref

class SearchedFoodRow extends React.Component {
  componentDidMount() {
    c3.generate({
      bindTo: this.element,
      ...
    })
  }

  render() {
    const { food } = this.props

    return (
      <div>
        <label>{food.recipe.label}</label>
        <img className="card-img-top" src={food.recipe.image} height="250" width="auto"></img>
        <a href={food.recipe.url}>{food.recipe.source}</a>
        <p>{food.recipe.dietLabels[0]}</p>

        <div>
          {food.recipe.ingredientLines.map((ingredient, i) => {
            return (
              <p key={i}>{ingredient}</p>
            ) 
          })}
        </div>

        <p>Calories {Math.floor(food.recipe.calories/food.recipe.yield)}</p>
        <div ref={ element => this.element = element } />
      </div>
    )
  }
}

然后

class SearchFood extends React.Component {
  render() {
    return (
      <div>
        { this.props.foodResults.map((food, i) => <SearchedFoodRow key={i} food={food} />)}
      </div>
    )
  }
}