[英]React event delegation from parent to child
I have a Gatsby Link
element inside of an <li>
and I want the Link
element to be triggered if the <li>
is clicked with cursor or hit with the enter
key.我在
<li>
有一个 Gatsby Link
元素,如果使用光标单击<li>
或按enter
键,我希望触发Link
元素。
export default class Search extends Component {
...Constructor...
render() {
...DOM elements...
<input type="text" value={this.state.query} onChange={this.search} placeholder={'Search'} />
{this.state.results.map((page, index) => (
<li tabIndex={index} key={page.id} >
<Link to={"/" + page.path}>{page.title}</Link>
</li>
))}
...DOM elements...
}
...More functions...
}
The above code is inside of a render
block, which is inside of a class which extends Component
.上面的代码位于
render
块内,该render
块位于扩展Component
的类内。
I've tried adding an onClickHandler
to the <li>
, but don't know of any object I can pass to it which contains a reference to its child...我已经尝试向
<li>
添加一个onClickHandler
,但不知道我可以传递给它的任何包含对其子项的引用的对象......
The main reason I need the event delegation to the child is because the tabIndex
(which receives focus from the input
element above it) only works on the <li>
, so once the <li>
has focus, I want the user to be able to hit enter and have that event propogate to the child <Link>
element (which is a special link element using Gatsby's internal routing).我需要将事件委托给孩子的主要原因是因为
tabIndex
(从其上方的input
元素接收焦点)仅适用于<li>
,因此一旦<li>
获得焦点,我希望用户能够点击 Enter 并让该事件传播到子<Link>
元素(这是一个使用 Gatsby 内部路由的特殊链接元素)。
You can pass the current page.path
as well as the event directly to your handler, onKeyPress={e => this.goTo(e, page.path)}
.您可以将当前
page.path
以及事件直接传递给您的处理程序onKeyPress={e => this.goTo(e, page.path)}
。
Example.例子。
import { navigate } from "gatsby"
export default class Search extends Component {
... redacted for brevity ...
goTo = (e, path) => {
if (e.Key === "Enter") {
navigate(`/${path}`);
}
};
render() {
... redacted for brevity ...
{
this.state.results.map((page, index) => (
<li tabIndex={index} key={page.id} onKeyPress={e => this.goTo(e, page.path)}>
<Link to={"/" + page.path}>{page.title}</Link>
</li>
));
}
... redacted for brevity ...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.