我想知道执行此操作的最佳方法是什么。
我有 3 个组件:App、String 和 Note。在我像这样在应用程序中创建注释元素之前:
<Note
state={this.state.btnStates[i]}
onClick={() => this.handleClick(i)}
/>
它的工作方式就像魅力(handleClick 当然是在最父组件 - 应用程序中)
但现在我想将注释创建转移到 String 组件,我认为这很容易,但我认为可行的方法却并非如此。我这样做是这样的: 在应用程序组件中我渲染字符串:
<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>
);
}
在注释组件中:
<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}
访问它,我为此目的创建了另一个属性“id”,它作品。我现在还有另一个问题,即使在 App 构造函数中绑定(bind)后,登录到 handleClick 函数的 this
也不会显示 App 组件,而是显示 Note 本身:/
最佳答案
在不使用 Context 或 Redux 之类的状态处理程序的情况下,React 的做法是将函数作为 props 传递。
App.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,但您应该这样做,因为使用索引作为键可能会导致问题。
关于javascript - 如何从子组件的子组件调用处理函数(ReactJS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59235657/