【发布时间】:2016-05-13 18:07:20
【问题描述】:
我在使用 componentDidMount() 中的 setState 函数时遇到了一些问题。
我正在尝试做的事情:我正在尝试使 HTML5 圆圈响应(如果浏览器窗口更大,则变大,反之亦然)。
到目前为止我所做的:我一直将维度存储在名为 containerDim 的状态中。默认情况下,这设置为 null。这是我所做的一个非常基本的实现:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {containerDim: null};
this.resizeCircle = this.resizeCircle.bind(this) //To not loose value of this
}
componentDidMount() {
var dimensions = window.getComputedStyle(this.refs.responsiveContainer); //Used to get width and height
this.setState({
containerDim: {width:dimensions.width, height: dimensions.height}
});
window.addEventListener("resize", this.resizeCircle));
}
resizeCircle() { //THE RESIZING WORKS, THE initial setting of state doesn't
var dimensions = window.getComputedStyle(this.refs.responsiveContainer); //Used to get width and height
this.setState({
containerDim: {width:dimensions.width, height: dimensions.height}
});
}
render() {
return (
<div ref={"responsiveContainer"} >
<Circle dimensions={this.state.containerDim} />
</div>
);
}
}
//Circle component
class Circle extends React.Component {
constructor(props) {
super(props);
}
componentWillReceiveProps() {
console.log(this.props.dimensions); //THIS LOGS OUT NULL
}
render() {
CIRCLE GOES HERE
}
}
基本上,我试图用这段代码做的是获取“responseContainer”的宽度和高度,并将其作为道具传递给<Circle /> 组件。
上述不起作用,因为 setState 不会改变任何状态。
任何帮助将不胜感激!
编辑:
这个“有效”但我觉得它不正确,应该有更好的方法:
var dimensions = window.getComputedStyle(this.refs.container);
setTimeout(function() {
this.setState({
screenDim:{width:dimensions.width, height:dimensions.height}
});
}.bind(this),0);
this.setState({
screenDim:{width:dimensions.width, height:dimensions.height}
});
【问题讨论】:
-
你有什么错误吗?
-
问题是,当我调用 setState 时,实际上没有任何变化。containerDim 仍将为空。问题是 setState 只有在我调用它两次时才会做某事。更奇怪的是,即使 setState 没有改变任何东西,它仍然调用 componentWillReceiveProps..
-
与问题无关,但为什么不直接使用 CSS(流体宽度)来调整圆的大小?
-
你可以为 HTML 画布圈做这个吗?如果是这样,我可能会看一下,但我认为无论如何这对我来说都是一次很好的学习经历
-
哦,你是用画布作画的,没关系:)
标签: javascript reactjs state