教程1-14完整项目地址 https://github.com/x1141300029/react-Todos.git
1.引用包src/components/TodoInput/index.js
import React, {Component,createRef} from 'react'; // #updatet修改
2.在constructor
中创建ref
(src/components/TodoInput/index.js
)
//构造函数
constructor(props) {
super(props);
this.state = {
inputValue: ''
};
this.inputDom=createRef(); //insert 新增
}
3.引用ref
(src/components/TodoInput/index.js
)
render() {
return (
<div>
<input
onChange={this.handleInputChange}
onKeyUp={this.handleKeyUp}
value={this.state.inputValue}
type="text"
ref={this.inputDom} #insert 新增
/>
<button onClick={this.handleAddClick}>{this.props.btnText}</button>
</div>
);
}
4.添加完list后自动获取dom焦点src/components/TodoInput/index.js
//点击添加事件
handleAddClick = () => {
//调用父组件的addTodos函数,并把当前输入框内容传递过去
this.props.addTodos(this.state.inputValue);
this.setState({
inputValue:''
},()=>{
this.inputDom.current.focus();//获取dom焦点
})
};
网友评论