Jor*_*son 3 javascript jquery reactjs
我正在尝试使用 jQuery 库 (Highcharts) 在 React 组件中呈现数据。
据我了解,我需要将 jQuery 代码放在 componentDidMount() 函数中才能正确运行。它确实如此,只要我在 componentDidMount() 方法中包含静态数据。
但我想将 jQuery 代码连接到我的数据库,以便图表是反应式的。我读到 componentDidMount() 只运行一次,所以我怀疑我将无法在其中放置反应数据(我什至无法让道具登录到控制台......它们总是未定义)。
我可以将 props 传递给 componentDidUpdate(),但是我的 jQuery 代码不显示。
有人有解决方案吗?
谢谢!!
您可以使用.setDataHighcharts 提供的方法。每次收到新道具时都可以更新数据。这是一个非常基本的示例,显示了这一点:
class Chart extends React.Component {
constructor() {
super();
// Init state.
this.state = { chart: {} };
}
componentDidMount() {
const _this = this;
// Init chart with data from props.
var chart = Highcharts.chart('chart', {
series: [{ data: _this.props.data }]
});
// Save the chart "container" in the state so we can access it from anywhere.
this.setState({ chart });
}
componentWillReceiveProps(props) {
// Update the chart with new data every time we receive props.
this.state.chart.series[0].setData(props.data);
}
render() {
return <div id="chart" />;
}
}
class App extends React.Component {
constructor() {
super();
// Set some initial data.
this.state = { data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]};
this.changeData = this.changeData.bind(this);
}
changeData() {
// Update with a different dataset.
this.setState({
data: [129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4],
});
}
render() {
return(
<div>
<button onClick={this.changeData}>Change Data</button>
<Chart data={this.state.data} />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('View'));Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="View"></div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19752 次 |
| 最近记录: |