我有一个按钮,当它被点击时,应该将按钮颜色更改为红色。我通过更改状态来更新组件的类以使其变为 .red 类,从而更新颜色,并在 4 秒后将其恢复为正常状态。然而,某种原因导致它没有更新和重新渲染组件。
我的代码:
import React from "react";
import ReactDom from "react-dom";
const app = document.getElementById("app");
class Layout extends React.Component{
constructor(props){
super(props);
this.users =[
{
name:"user1",
world:"88",
},{
name:"user12",
world:"882",
},{
name:"user13",
world:"883",
},{
name:"user14",
world:"884",
},{
name:"user14",
world:"884",
},{
name:"user15",
world:"885",
},{
name:"user16",
world:"886",
},{
name:"user17",
world:"8867",
},{
name:"user18",
world:"8868",
}
];
this.ulist = this.users.map((user, i) => {
var cName = i<5 ? "active":"nonActive";
return <div key = {i} className = {cName}><h4>{user.name}</h4><p>{user.world}</p></div>;
});
this.state = {
lastUser:4,
firstUser:0,
errorUp:"",
errorDown: "",
};
}
moveUp(){
this.state.errorUp = "red";
setTimeout(() =>{
this.state.errorUp = "";
},4000);
}
render(){
return(
<div>
<i className={"fa fa-caret-up arrow "+ this.state.errorUp} aria-hidden="true" onClick = {this.moveUp.bind(this)}></i>
<i className={"fa fa-caret-down arrow "+ this.state.errorDown} aria-hidden="true"></i>
{this.ulist}
</div>
);
}
}
ReactDom.render(<Layout/>,app);
为什么会发生这种情况?是否有其他方法可以向组件添加类以便更新?谢谢您的时间;
this.setState
,而不是改变this.state
。另外,你应该在你的render
函数中使用users.map()
。 - Aaron Beallthis.setState({ errorUp : "red"})
。这样可以吗? - Pierfrancesco