[英]React js : change background color for specific item in list of items
我有我的變量 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);
但她沒有檢測到我何時點擊了一個新項目,有人可以幫助我嗎,謝謝
我可以為您提供一個簡單的演示如何使用工作示例。
您可以根據您的要求進行更改。 現場演示
代碼
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>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.