我想将“main.js”(父组件)的this.state传递给“bar.js”(子组件)。reactjs无法将this.props传递给react-chartist
//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 VS this.props有点糊涂了。在这种情况下,我是否正确使用this.props来处理它?
如果标签的值,一系列组件在运行时基于用户交互或其他外部条件发生变化,那么它更好地使用状态,因为然后将新值设置为状态会自动渲染组件。如果标签的值,组件系列是恒定的,并且在其初始渲染之后永远不会改变,那么它最好只使用道具。 –