[英]array map react component call child function
如果我們在反應中使用數組映射,我們如何調用子函數? 我找到了一種使用 refs 進行谷歌搜索的方法,但它不會調用實際組件,而不是它注冊的最后一個組件。
索引.jsx
setActiveChat = (ID) => {
this.refs.chateditor.activateChat(ID);
}
{
this.state.users.map((user, index) => <ChatEditor ref="chateditor"/>)
}
聊天編輯器.jsx
activateChat = (ID) => {
alert("Hi i am here!");
}
謝謝@Mayank Shukla
通過從他的解決方案中獲得啟發,並根據DOC避免使用 refs,如果有人想使用它,我想出了一個解決方案。
索引.jsx
setActiveChat = (ID) => {
this[`editor${ID}`](ID);
}
{
this.state.users.map((user, index) => <ChatEditor initChat={edtr =>
(this[`editor${user.ID}`] = edtr)} />
}
聊天編輯器.jsx
constructor(props) {
super(props);
props.initChat(this.activateChat);
}
activateChat = (ID) => {
alert('Hey, I m here')
}
因為您為所有子組件分配了相同的 ref(引用名稱),所以在循環結束時,ref 將具有最后一個子組件的引用。
解決方案是,為每個子元素使用唯一的 ref 名稱,一種實現方法是將元素的索引與 ref 放在一起。
像這樣:
this.state.users.map((user, index) => <ChatEditor ref={`chateditor${index}`} />)
現在使用:
this.refs[`chateditor${index}`] //replace index with 0,1,2...
訪問特定的子元素。
建議,根據DOC :
如果您之前使用過 React,您可能熟悉舊 API,其中 ref 屬性是一個字符串,如“textInput”,並且 DOM 節點作為 this.refs.textInput 訪問。 我們建議不要這樣做,因為字符串引用有一些問題,被認為是遺留的,並且可能會在未來的版本之一中被刪除。 如果您當前正在使用 this.refs.textInput 來訪問 refs,我們建議您改用回調模式。
所以使用 ref 回調方法而不是字符串 refs。
像這樣:
this.state.users.map((user, index) =>
<ChatEditor ref={el => (this[`chateditor${index}`] = el)} />)
現在使用它來訪問子組件:
this[`chateditor${index}`] //replace index with 0,1,2...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.