首页 > 解决方案 > 在 React 中,如何在 render() 运行之前将元素放到 DOM 上?

问题描述

我正在使用 React(带有 Rails)并使用一个名为 AnyChart 的图表库。但是,我在渲染中拥有的 AnyChart 代码会自动查找<div id="container"></div>要附加图表的元素。如果我将图表代码与容器 div 一起放入渲染中,则会出现错误,因为图表代码找不到 div,因为它还没有在 DOM 上。

我尝试使用谷歌搜索,只发现有关门户和参考的内容似乎不适用于我的问题。

我知道我可以将容器 div 移动到布局视图模板,但我希望能够在图表下方的组件上呈现其他内容。这是我的整个 StockContainer 组件和 InputField 组件:

import React from 'react';
import InputField from '../components/InputField'

class StockContainer extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      stockTicker: ''
    }
    this.handleStockTickerChange = this.handleStockTickerChange.bind(this);
    this.handleClearForm = this.handleClearForm.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleClearForm(event){
    event.preventDefault();
    this.setState({
      stockTicker: ''
    });
  }

  handleStockTickerChange(event) {
    this.setState({stockTicker: event.target.value});
  }

  handleSubmit(event){
    event.preventDefault();

    let body = {
      symbol: this.state.stockTicker
    }
    console.log("Getting stock data for: " + body.symbol)
    this.handleClearForm(event);
  }

  componentDidMount() {
  }

  render() {

    var table, mapping, chart;

    table = anychart.data.table();
    table.addData([
    ['2015-12-25', 512.53, 514.88, 505.69, 507.34],
    ['2015-12-26', 511.83, 514.98, 505.59, 506.23],
    ['2015-12-27', 511.22, 515.30, 505.49, 506.47],

     ...sample data that will later be imported from an API
 
    ['2016-01-07', 510.93, 516.07, 506.00, 510.99],
    ['2016-01-08', 510.88, 515.93, 505.22, 509.95],
    ['2016-01-09', 509.12, 515.97, 505.15, 510.12],
    ['2016-01-10', 508.53, 516.13, 505.66, 510.42]
    ]);

    // mapping the data
    mapping = table.mapAs();
    mapping.addField('open', 1, 'first');
    mapping.addField('high', 2, 'max');
    mapping.addField('low', 3, 'min');
    mapping.addField('close', 4, 'last');
    mapping.addField('value', 4, 'last');

    // defining the chart type
    chart = anychart.stock();

    // set the series type
    chart.plot(0).ohlc(mapping).name('ACME Corp.');

    // setting the chart title
    chart.title('AnyStock Demo');

    // display the chart
    chart.container('container');
    chart.draw();

    return(
      <div>
        <h1>Research/Add a Stock</h1>
        <form onSubmit={this.handleSubmit}>
          <InputField
            label='Stock Symbol'
            name='ticker'
            content={this.state.stockTicker}
            handleChange={this.handleStockTickerChange}
          />
          <input type='submit' value='Get Info'/>
        </form>
        <div id="container"></div>
      </div>
    )
  }
}

export default StockContainer;

import React from 'react';

const InputField =(props) =>{
  return(
    <label>{props.label}
      <input
      type='text'
      name={props.name}
      value={props.content}
      onChange={props.handleChange}
      />
    </label>
  )
}
 export default InputField

标签: javascriptreactjs

解决方案


就像上面评论中提到的 Ishwor 一样,您是否尝试过将chart.container()andchart.draw()方法移动到组件的componentDidMount()钩子中?

如果您可以为您的组件提供其余代码,我们或许可以提供帮助。

import React from 'react';
import InputField from '../components/InputField'

class StockContainer extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      stockTicker: ''
    }

    let table = anychart.data.table();
    table.addData([
    ['2015-12-25', 512.53, 514.88, 505.69, 507.34],
    ['2015-12-26', 511.83, 514.98, 505.59, 506.23],
    ['2015-12-27', 511.22, 515.30, 505.49, 506.47],

    ...sample data that will later be imported from an API
    ]);

    // mapping the data
    let mapping = table.mapAs();
    mapping.addField('open', 1, 'first');
    mapping.addField('high', 2, 'max');
    mapping.addField('low', 3, 'min');
    mapping.addField('close', 4, 'last');
    mapping.addField('value', 4, 'last');

    // defining the chart type
    let chart = anychart.stock();

    // set the series type
    chart.plot(0).ohlc(mapping).name('ACME Corp.');

    // setting the chart title
    chart.title('AnyStock Demo');

    // to be able to reference these later, if needed
    this.table = table;
    this.mapping = mapping;
    this.chart = chart;

    this.handleStockTickerChange = this.handleStockTickerChange.bind(this);
    this.handleClearForm = this.handleClearForm.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);

    // draw the chart
    this.drawMyAwesomeChart = this.drawMyAwesomeChart.bind(this);
  }

  componentDidMount() {
    this.chart.container('container');
    this.drawMyAwesomeChart()
  }

  componentDidUpdate() {
    // do some checks here to see if you need to draw chart?
    // this.drawMyAwesomeChart()
  }

  drawMyAwesomeChart() {
    this.chart.draw();
  }

}

然后,您可以绑定一个专门负责在股票代码更改时刷新图表的函数。我还没有完全测试过这个,但是这些方面的东西应该有效吗?


推荐阅读