[英]How do I render one of several of the same react component?
I dont know if my brain is extra mushy today or what.我不知道我今天的大脑是不是特别糊状还是什么。 Im trying to learn react and now I have a list of messages that is rendered from an array.我试图学习反应,现在我有一个从数组呈现的消息列表。 Inside every message I have a button to render the "send message" component to answer the message.在每条消息中,我都有一个按钮来呈现“发送消息”组件来回答消息。 My problem is that when I press the button "answer", All the message-items in the list renders the 'send message' component.我的问题是,当我按下“回答”按钮时,列表中的所有消息项都会呈现“发送消息”组件。 How do I bind it to just one message I clicked answer in?如何将它绑定到我点击回答的一条消息? See my code and you will understand my question:看看我的代码,你就会明白我的问题:
render() {
let messages = this.state.messages.map((item, key) =>
<div>
<ul key={item.id} className="messageList">
<li><h3 className="messageTitle">{item.title}</h3></li>
<li>{item.message}</li>
<li className="messageSignature">from: {item.from}</li>
</ul>
{this.state.showSendMessage ? <SendMessage recipient={item.from} title={item.title}></SendMessage> : null}
<button onClick={this.toggleShowSendMsg.bind(this)}>Answer</button>
</div>
);
Its because your state variable "showSendMessage" is not unique to any particular message and hence its becoming true for all the elements of messages.这是因为您的 state 变量“showSendMessage”对于任何特定消息都不是唯一的,因此对于消息的所有元素都适用。
Add one more state variable as "key".再添加一个 state 变量作为“键”。
render() {
let messages = this.state.messages.map((item, key) =>
<div>
<ul key={item.id} className="messageList">
<li><h3 className="messageTitle">{item.title}</h3></li>
<li>{item.message}</li>
<li className="messageSignature">from: {item.from}</li>
</ul>
{this.state.showSendMessage && this.state.key == key ? <SendMessage recipient={item.from} title={item.title}></SendMessage> : null}
<button onClick={this.toggleShowSendMsg.bind(key)}>Answer</button>
</div>
);
and change the state of key in your toggleShowSendMsg method the way you are doing for showSendMessage.并按照您对 showSendMessage 所做的方式更改您的 toggleShowSendMsg 方法中的密钥 state。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.