11.使用ref的方式获取dom元素`实现添加list以后自动获

2020-05-21  本文已影响0人  __疯子__

教程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焦点
        })
    };
上一篇 下一篇

猜你喜欢

热点阅读