我有我的变量messageInbox是将由.map显示的消息数组,如下所示
{messageInbox
.map((chat ,index)=> (
<Inbox chat={chat} backgroundColor={this.state.backgroundColor} inBox={this.props.inBox} setInBox={this.props.setInBox} tourists={this.state.tourists.filter(x => x.hotel_id == this.context.hotel_id[0])} chats={this.props.chats} key={index} />
))
}
我想通过div中的onClick事件更改被单击项的背景颜色
class Inbox extends Component
constructor(props) {
super(props);
this.state = {
backgroundColor:'#2e405e'
}
}
render() {
return (
<div className="InboxContainer" style={{backgroundColor:this.state.backgroundColor}}
onClick={ this.setState({backgroundColor:'#111f35'}) } >
<div className="ImageMsg">
<img src="/img/chat/contact.png" className="imgContact" />
</div>
<div className="TextMsg">
{this.props.tourists.map(name => {
return name.id == this.props.chat.sender ?
<p className="nameContact"> {name.nom}</p>
: ""
})}
{/* <p className="nameContact"> {this.props.chat.sender}</p> */}
<p className="msgContact">
{this.props.chat.message}
</p>
</div>
{/* <div className="TimeMsg"> */}
{/* <p>{this.props.chat.time}</p> */}
{/* <ReactSVG
src="/img/chat/notSeen.svg"
className="svgIconSeensend"
/>
</div>
*/}
</div>
);
}
}
Inbox.contextType = UserContext
export default withRouter(Inbox);
但是当我单击一个新项目时,她没有发现,谢谢您的帮助。
答案 0 :(得分:2)
我可以为您提供一个简单的演示,以演示如何使用示例。
您可以根据需要进行更改。 Live demo
代码
class App extends React.Component {
state = {
arr: [
{ id: 1, name: "profile", title: "Profile" },
{ id: 2, name: "recruit", title: "Recruitment" },
{ id: 3, name: "arts", title: "Arts" },
{ id: 4, name: "talents", title: "Talents" },
{ id: 5, name: "affection", title: "Affection" }
],
selected: ""
};
changeColor = id => {
this.setState({ selected: id });
};
render() {
const { selected, arr } = this.state;
return (
<div>
<h2>Click to items</h2>
<ul>
{arr.map(({ name, id, title }) => (
<li key={id}>
<h3 style={{color: selected === id ? "red" : ""}}
onClick={() => this.changeColor(id)}
name={name}>
{title}
</h3>
</li>
))}
</ul>
</div>
);
}
}