Reactjs 无法在React应用程序中设置状态
我正在尝试在React中创建一个元素,该元素在加载页面后会淡入。 通过调试,我了解到setState并没有按照我希望的方式工作Reactjs 无法在React应用程序中设置状态,reactjs,Reactjs,我正在尝试在React中创建一个元素,该元素在加载页面后会淡入。 通过调试,我了解到setState并没有按照我希望的方式工作 const divHeight = 100; const divWidth = 300; class ProbaShell extends React.Component{ constructor(props){ super(props); this.state = { h: divHeight, w: divWidth
const divHeight = 100;
const divWidth = 300;
class ProbaShell extends React.Component{
constructor(props){
super(props);
this.state = {
h: divHeight,
w: divWidth
};
this.fadeIn = this.fadeIn.bind(this);
}
fadeIn(){
// alert('fadeInFunc');
var divH = document.getElementById('kwadrat').clientHeight;
while(divH <= 400){
divH = divH + 5;
this.setState({ h: divH });
var sh = this.state.h;
};
}
render(){
return(
<Proba style = {{height: this.state.h}}/>
)
}
componentDidMount(){
alert('fadeInCall');
this.fadeIn();
}
}
const divHeight=100;
常数divWidth=300;
类ProbaShell扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
h:高度,
w:等宽
};
this.fadeIn=this.fadeIn.bind(this);
}
法代因(){
//警报(“fadeInFunc”);
var divH=document.getElementById('kwadrat').clientHeight;
while(divH首先,我希望您提供TIPP以优化代码:
使用箭头函数而不是bind():
在这种情况下,只需调用如下方法即可:
this.fadeIn();
你能给我更多关于你想做什么以及组件是如何构造的信息吗(父/子)。我永远不会在React应用程序中使用document.getElementById…你的代码中有三个问题:
while
循环太快,你看不到任何运动。为了解决这个问题,我在下面提出了一个setInterval
解决方案
您给
组件赋予样式,认为它是默认的HTML属性。实际上它只是一个道具,下面的解决方案也解决了这一问题
您在道具定义中的=
标志周围放置空格,不建议这样做
以下是Proba
组件的渲染方法:
function render() {
return (
// set the style as a normal prop, it will work here because this
// is a simple <div>, not a component
<div ref="kwadrat" id="kwadrat" style={ this.props.style }>
kwadrat
</div>
);
}
我添加了一个显示工作示例的,其中我添加了两种不同的配置,用于移动
(步骤和时间)。这是什么意思:this.setState({h:divH},()=>console.log(this.state.h));
或者您是如何调试您的工作流并确定setState
不起作用的?您不应该像这样使用警报,因为它会阻止流程,这可能是您的代码不起作用的原因。如果您需要跟踪正在发生的事情,请使用console.log。循环是否会产生任何结果?
this.fadeIn();
function render() {
return (
// set the style as a normal prop, it will work here because this
// is a simple <div>, not a component
<div ref="kwadrat" id="kwadrat" style={ this.props.style }>
kwadrat
</div>
);
}
fadeIn() {
const interval = setInterval(() => {
this.setState({ h: (this.state.h + 5) });
if (this.state.h >= 400) {
clearInterval(interval);
}
}, 50);
}