我正在学习来自:http://ahmadchatha.com/writings/article1.html 的教程
它会像这样设置一个 React 组件:
class SimplePie extends React.Component {
render() {
return (
<div className="col-xs-4 chart"
style={{background: this.props.data[1]}} >
{this.props.title}
<D3Chart
width={200}
height={200}>
<DataSeries
data={this.props.data[0]}
colors={colors}
width={200} height={200} />
</D3Chart>
</div>
)
}
}
但我想更改此设置,以便 D3Chart 将根据父级的大小调整大小,并监听调整大小事件。在 React 中有什么简单的方法可以做到这一点吗?
我正在努力使用事件监听器来调整特定 div 上的事件大小。
最佳答案
用 React 测量元素的大小并不像您想象的那么简单,主要原因是 React 并不真正关心大小,您必须在绘制后从 DOM 中读取它们。
对于您这里的情况,我们可以在窗口
元素,像这样:
class SimplePie extends React.Component {
constructor (props, context) {
super(props, context);
this.state = {
width: 200,
height: 200
};
this.measure = this.measure.bind(this);
}
componentWillMount () {
window.addEventListener('resize', this.measure, false);
}
componentWillUnmount () {
window.removeEventListener('resize', this.measure, false);
}
measure () {
let rect = this.container.getBoundingClientRect();
if(this.state.width !== rect.width || this.state.height !== rect.height){
this.setState({
width: rect.width,
height: rect.height
});
}
}
componentDidMount (){
this.measure();
}
componentDidUpdate (){
this.measure();
}
render() {
return (
<div ref={(container)=>{this.container = container}} style={{width: "100%", height: 300}} className="col-xs-4 chart"
style={{background: this.props.data[1]}} >
{this.props.title}
<D3Chart
width={this.state.width}
height={this.state.height}>
<DataSeries
data={this.props.data[0]}
colors={colors}
width={this.state.width} height={this.state.height} />
</D3Chart>
</div>
)
}
}
编辑:容器必须有固定的宽度和高度,如果你想使用基于百分比的高度你必须设置这个组件的父级的高度。
关于javascript - 在 React 中将 D3 图表调整为父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39174159/