How can I add onKeyPress event to react material-ui textfield?

不问归期 提交于 2019-12-23 07:49:10

问题


I used a TextField from react material-ui. I want to know whether the user has pressed Ctrl+Enter. I have tried using onKeyPress event but got no result. How can I achieve this?

<TextField
    value={this.state.message}
    autoFocus={true}
    hintText='Type your message here'
    onChange={this.onChangeMessage}
    onKeyPress={(event) => {
        if (event.ctrlKey && event.keyCode == '13')
            this.sendMessage();
    }}
    multiLine={true}
/>

回答1:


onKeyPress is a synthetic Key event that React supports as mentioned here. Try this code:

 onKeyPress= (e) => {
            if (e.key === 'Enter') {
              console.log('Enter key pressed');
              // write your functionality here
            }
    }



回答2:


Please update the onKeyPress event with the below code

if ((event.keyCode == 10 || event.keyCode == 13) && event.ctrlKey)

Please see the link for Key Code Values



来源:https://stackoverflow.com/questions/45993523/how-can-i-add-onkeypress-event-to-react-material-ui-textfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!