这是我的表单和onClick方法。我想在按下键盘的Enter按钮时执行此方法。怎么样 ?
N.B:不赞赏jquery。
comment: function (e) {
e.preventDefault();
this.props.comment({comment: this.refs.text.getDOMNode().value, userPostId:this.refs.userPostId.getDOMNode().value})
},
<form className="commentForm">
<textarea rows="2" cols="110" placeholder="****Comment Here****" ref="text" /><br />
<input type="text" placeholder="userPostId" ref="userPostId" /> <br />
<button type="button" className="btn btn-success" onClick={this.comment}>Comment</button>
</form>
答案 0 :(得分:130)
将<button type="button"
更改为<button type="submit"
。删除onClick
。相反,<form className="commentForm" onSubmit={this.onCommentSubmit}>
。这应该点击按钮并按回车键。
修改:正如詹姆斯在评论中所说,你也可以在回调中拨打event.preventDefault()
来停止尝试加载action
网址的网页。
如果您想在回调中使用this
,您可以在构造函数中使用箭头函数:onSubmit={(e) => this.onCommentSubmit(e)}
或this.onCommentSubmit = this.onCommentSubmit.bind(this)
,甚至可以使用e7的箭头方法onCommentSubmit = (e) => {...}
。
onFormSubmit = e => {
e.preventDefault();
const { name, email } = this.state;
// send to server with e.g. `window.fetch`
}
...
<form onSubmit={this.onFormSubmit}>
...
<button type="submit">Submit</button>
</form>
答案 1 :(得分:8)
使用keydown
事件来执行此操作:
input: HTMLDivElement | null = null;
onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>): void => {
// 'keypress' event misbehaves on mobile so we track 'Enter' key via 'keydown' event
if (event.key === 'Enter') {
event.preventDefault();
event.stopPropagation();
this.onSubmit();
}
}
onSubmit = (): void => {
if (input.textContent) {
this.props.onSubmit(input.textContent);
input.focus();
input.textContent = '';
}
}
render() {
return (
<form className="commentForm">
<input
className="comment-input"
aria-multiline="true"
role="textbox"
contentEditable={true}
onKeyDown={this.onKeyDown}
ref={node => this.input = node}
/>
<button type="button" className="btn btn-success" onClick={this.onSubmit}>Comment</button>
</form>
);
}
答案 2 :(得分:2)
如果您想听“ Enter”键,这就是您的方法。 您可以使用一个onKeydown道具,您可以在react doc
中了解它。<nav class="navbar navbar-default">
<div class="container-fluid">
<ul class="nav nav-pills nav-fill">
<li class="nav-item col-md-3">
<a href="/people" routerLink="/people" routerLinkActive="active">People</a>
</li>
<li class="nav-item col-md-3">
<a href="/planets" routerLink="/planets" routerLinkActive="active">Planets</a>
</li>
<li class="nav-item col-md-3">
<a href="/starships" routerLink="/starships" routerLinkActive="active">Starships</a>
</li>
</ul>
</div>
</nav>
<select>
<option></option>
</select>
答案 3 :(得分:1)
自上次回答这个问题以来已经有好几年了。 React在2017年推出了“ Hooks”,而“ keyCode”已被弃用。
现在我们可以这样写:
useEffect(() => {
const listener = event => {
if (event.code === "Enter" || event.code === "NumpadEnter") {
console.log("Enter key was pressed. Run your function.");
// callMyFunction();
}
};
document.addEventListener("keydown", listener);
return () => {
document.removeEventListener("keydown", listener);
};
}, []);
这是在第一次加载组件时在keydown
事件上注册一个侦听器。销毁组件后,它将删除事件侦听器。
答案 4 :(得分:1)
import React , {useEffect , useRef } from 'react' ;
function Example() {
let inp = useRef()
useEffect(()=>{
if (!inp && !inp.current) return
inp.current.focus() ;
return () => inp = null ;
});
const handleSubmit = () => {
//...
}
return (
<form
onSubmit={(e) => {
e.preventDefault();
handleSubmit(e);
}} >
<input
name="fakename"
defaultValue="...."
ref={inp}
type="text"
style={{
position :"absolute" ,
opacity : 0
}}
/>
<button type="submit">
submit
</button>
</form>
)
}
有时会在popus中输入代码,因为绑定可能没有任何输入,所以仅绑定表单并把onSubmit传递给表单是行不通的。在这种情况下,如果您通过执行document.addEventListener
将事件绑定到文档,这将在应用程序的其他部分引起问题,因为这可以解决此问题,我们应该包装一个表单并输入一个隐藏的CSS ..
那么您就可以通过ref集中查看该输入,从而可以正常工作。
答案 5 :(得分:1)
如果您在 <form>
中没有表单,您可以在 componentDidMount()
中使用它:
componentDidMount = () => {
document.addEventListener("keydown", (e) =>
e.code === "Enter" && console.log("my function"))
}
componentDidMount() //<-- remove this, it's just for testing here
答案 6 :(得分:0)
我已经建立在@ user1032613的答案和this answer的基础上,并创建了一个“按下时输入带有查询字符串的单击元素”钩子。享受!
const { useEffect } = require("react");
const useEnterKeyListener = ({ querySelectorToExecuteClick }) => {
useEffect(() => {
//https://stackoverflow.com/a/59147255/828184
const listener = (event) => {
if (event.code === "Enter" || event.code === "NumpadEnter") {
handlePressEnter();
}
};
document.addEventListener("keydown", listener);
return () => {
document.removeEventListener("keydown", listener);
};
}, []);
const handlePressEnter = () => {
//https://stackoverflow.com/a/54316368/828184
const mouseClickEvents = ["mousedown", "click", "mouseup"];
function simulateMouseClick(element) {
mouseClickEvents.forEach((mouseEventType) =>
element.dispatchEvent(
new MouseEvent(mouseEventType, {
view: window,
bubbles: true,
cancelable: true,
buttons: 1,
})
)
);
}
var element = document.querySelector(querySelectorToExecuteClick);
simulateMouseClick(element);
};
};
export default useEnterKeyListener;
这是您的用法:
useEnterKeyListener({
querySelectorToExecuteClick: "#submitButton",
});
https://codesandbox.io/s/useenterkeylistener-fxyvl?file=/src/App.js:399-407
答案 7 :(得分:0)
这是非常优化的代码
useEffect(() => {
document
.getElementById("Your-element-id")
.addEventListener("keydown", function (event) {
if (event.code === "Enter" || event.code === "NumpadEnter") {
event.preventDefault();
document.getElementById("submit-element").click();
}
});
}, []);
答案 8 :(得分:-1)
例如下一个 React+TS 代码(添加用于状态等的钩子):
type Props = {
...any properties
} & [any other type if need]
//I want notice that input data type of component maybe difference from type of props
const ExampleComponent: React.FC<Props> = (props: [Props or any other type]){
const anySerice = new AnyService();
const handleSubmit = async (eventForm) => {
await anySerice.signUp();
}
const onKeyUp = (event: KeyboardEvent) => {
//you can stay first condition only
if (event.key === 'Enter' || event.charCode === 13) {
handleSubmit(event)
}
}
...other code
return (<Form noValidate validated={validated} className="modal-form-uthorize" onKeyPress={onKeyUp}>
...other components form
</Form>)
}
export default ExampleComponent;