我创建了一个待办事项应用程序,它工作正常。但我想,当我按下enter显示任务。 onclick和onchange事件运行正常。需要onkeypress事件事件添加为好。
import React, { Component } from 'react'
class Todolist extends Component {
constructor(props) {
super(props)
this.state = {
userinput : "",
list : [],
title : " My simple todo app"
}
}
/
changeUserInput (input){
this.setState({
userinput : input
})
}
addToList (input){
const listArray = this.state.list
listArray.push(input);
this.setState ({
list : listArray,
userinput : "",
})
}
render() {
return (
<div className="todolistmain">
<h2 style={{color:"red"}} >{this.state.title}</h2>
<input
onChange={(e)=>this.changeUserInput(e.target.value)}
onKeyPress={e => {
if (e.key === 'Enter') {
this.changeUserInput()
}
}}
value={this.state.userinput} type="text"
placeholder="Enter task!!"/>
<button style={{color:"blue"}} onClick={()=>this.addToList(this.state.userinput)}>New Task</button>
<ul style={{color:"green"}}>
{this.state.list.map((val)=><li>{val}</li>)}
</ul>
</div>
)
}
}
export default Todolist
答案 0 :(得分:0)
使用keyCode
onKeyPress={e => {
if (e.keyCode === 13) {
this.changeUserInput()
}
}}
class Todolist extends React.Component {
constructor(props) {
super(props)
this.state = {
userinput : "",
list : [],
title : " My simple todo app"
}
}
changeUserInput (input){
this.setState({
userinput : input
})
}
addToList (input){
const listArray = this.state.list
listArray.push(input);
this.setState ({
list : listArray,
userinput : "",
})
}
render() {
return (
<div className="todolistmain">
<h2 style={{color:"red"}} >{this.state.title}</h2>
<input
onChange={(e)=>this.changeUserInput(e.target.value)}
onKeyDown={e => {
if (e.keyCode === 13) {
this.addToList(this.state.userinput)
}
}}
value={this.state.userinput} type="text"
placeholder="Enter task!!"/>
<button style={{color:"blue"}} onClick={()=>this.addToList(this.state.userinput)}>New Task</button>
<ul style={{color:"green"}}>
{this.state.list.map((val)=><li>{val}</li>)}
</ul>
</div>
)
}
}
ReactDOM.render(<Todolist/> , document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'>
</div>