[英]Adding onKeyPress to existing <a onClick={}></a>
I have been attempting to add several onKeyPress to existing onClick tags in my React.js project, more specifically, being able to press Enter to fire off an onClick after tabbing to a link. 我一直在尝试将几个onKeyPress添加到我的React.js项目中的现有onClick标记中,更具体地说,是能够在选择链接后按Enter触发onClick。 The onKeyPress in my code works properly when I insert a simple console.log() to test, however it fails when I insert the function.
当我插入一个简单的console.log()进行测试时,代码中的onKeyPress可以正常工作,但是当我插入该函数时,它会失败。 I left out irrelevant portions of code for brevity.
为了简洁起见,我省略了不相关的代码部分。 Essentially I need click and Enter to do the same thing.
本质上,我需要单击和Enter才能执行相同的操作。 Thanks!!!
谢谢!!!
class Link extends React.Component {
changeSection(e) {
// code to change section
}
render() {
return (
<div>
<a id="menu-item" tabIndex={this.props.tabIndex} onKeyPress={(e) => {(e.key === 'Enter' ? this.changeSection.bind(this) : null)}} onClick={this.changeSection.bind(this)}>
{this.props.linkText}
</a>
</div>
);
}
}
Another option would be to let the browser handle it for you, especially because you're already using an a
tag. 另一种选择是让浏览器为您处理,特别是因为你已经在使用的
a
标签。 It might not be nice to add the href="#"
, but it's probably better than a function that is regenerated every render. 添加
href="#"
可能不是很好,但是它可能比在每个渲染器中重新生成的函数要好。 Plus you don't have the overhead with the custom tabbing implementation. 另外,自定义制表符实现没有开销。
Try it here: 在这里尝试:
class Link extends React.Component { changeSection(e) { e.preventDefault(); console.log('Fired!'); } render() { return ( <div> <a id="menu-item" href="#" onClick={this.changeSection.bind(this)} > {this.props.linkText} </a> </div> ); } } ReactDOM.render( <Link linkText="Test" />, document.getElementById('root') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>
It looks like a syntax error. 它看起来像语法错误。 Does this work?
这样行吗? If not, what error are you getting?
如果没有,您会得到什么错误?
<a id="menu-item" tabIndex={this.props.tabIndex} onKeyPress={(e) => (e.key === 'Enter') ? this.changeSection.bind(this) : null} onClick={this.changeSection.bind(this)}>
You mixed 2 syntax together I think. 我认为您将2种语法混合在一起。
You can change this; 您可以更改此设置;
onKeyPress={(e) => {(e.key === 'Enter' ? this.changeSection.bind(this) : null)}}
With this; 有了这个;
onKeyPress={(e) => {
if(e.key === 'Enter') this.changeSection.bind(this);
else null
}}
or with this; 或与此;
onKeyPress={(e) => (e.key === 'Enter' ? this.changeSection.bind(this) : null)}
onKeyPress={(e) => {(e.key === 'Enter' ? this.changeSection.bind(this) : null)}}
I think this is where you fail. 我认为这是您失败的地方。 Your code here just binds new context to a function but doesn't call it.
您的代码仅将新上下文绑定到函数,但未调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.