[英]How to call handler function from a child of a child component (ReactJS)
我想知道這樣做的最佳方法是什么。
我有 3 個組件,App、String 和 Note。 在我像這樣在 App 中創建 Note 元素之前:
<Note
state={this.state.btnStates[i]}
onClick={() => this.handleClick(i)}
/>
它就像魅力一樣工作(handleClick當然在最父組件 - 應用程序中)
但現在我想將筆記創建轉移到 String 組件,我認為這很容易,但我認為可行的事情卻沒有。 我是這樣做的:在 App 組件中,我呈現字符串:
<String
btnStates={this.state.btnStates}
onClick={(i) => this.handleClick(i)}
></String>
在字符串組件中:
for (var i = 0; i < stringLength; i++) {
notes.push(
<Note
key={i}
onClick={keyFromNoteCall => this.props.onClick(keyFromNoteCall)}
state={this.props.btnStates[i]}
></Note>
);
}
並在 Note 組件中:
<input
type="button"
className={this.getClassName(this.props.state)}
onClick={() => this.props.onClick(this.props.key)}
value={this.props.value}
disabled={this.isDisabled()}
/>
React 做這些事情的方式是什么? 我需要在應用程序中處理邏輯,但我想將 Notes 的渲染循環移動到另一個組件。
*更新:事實證明問題是“key”屬性,因為它無法使用{this.props.key}
訪問我{this.props.key}
創建了另一個屬性“id”並且它有效。 我現在有另一個問題,即使在 App 構造函數中綁定之后, this
登錄的 handleClick 函數也不會顯示 App 組件,而是顯示 Note 本身:/
在不使用 Context 或 Redux 之類的狀態處理程序的情況下,React 的做法是將函數作為 props 傳遞。
應用程序.js
<String
btnStates={this.state.btnStates}
handleClick={this.handleClick}
/>
字符串組件
for (var i = 0; i < stringLength; i++) {
notes.push(
<Note
key={i}
handleClick={this.props.handleClick}
state={this.props.btnStates[i]}
></Note>
);
}
音符組件
<input
type="button"
className={this.getClassName(this.props.state)}
onClick={() => this.props.handleClick(this.props.key)}
value={this.props.value}
disabled={this.isDisabled()}
/>
此外,我建議您在 String 組件中使用 .map() 而不是 for 循環。
notes.map(note =>
<Note key={note.id}
handleClick={this.props.handleClick}
state={note.btnStates}
)
這樣你就必須重構以在你的筆記上有 ID,但你應該這樣做,因為使用索引作為鍵可能會導致問題。
如果我理解正確,您應該將應用程序中的 onClick 更改為 this 並且應該這樣做。
<String
btnStates={this.state.btnStates}
onClick={this.handleClick}
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.