我想将 this.state 从“main.js”(父组件)传递到“bar.js”(子组件)。
//main.js
import React, { Component } from 'react';
import BarChart from './Bar-chart';
class Hero extends Component {
constructor(props) {
super(props);
this.state = {
labels: ['P1', 'P2', 'P3', 'P4', 'P5/P6'],
series: [[ 1, 2, 3, 4, 5 ]]
}
}
render() {
return (
<div className="header">
<div className="container">
<div className="row">
<BarChart data={this.props.labels, this.props.series}/>
</div>
</div>
</div>
</div>
);
}
};
export default Hero;
这是我的子组件:
//bar.js
import React, { Component } from 'react';
import ChartistGraph from 'react-chartist';
import Legend from 'chartist-plugin-legend';
class BarGraph extends Component {
constructor(props) {
super(props);
}
render() {
const option = {
height: '350px',
plugins: [
Legend({
legendNames: ['P1', 'P2', 'P3', 'P4', 'P5/P6'],
})
]
};
return (
<ChartistGraph
data={this.props.labels, this.props.series}
options={option}
type={'Bar'} />
);
}
barData() {
return ({
labels: ['P1', 'P2', 'P3', 'P4', 'P5/P6'],
series: [[ 8, 28, 40, 25, 9 ]]
});
};
}
export default BarGraph;
此外,对于何时应该使用 this.state 和 this.props,我仍然有些困惑。在这种情况下,我是否使用 this.props 正确地接近它?