React use of the ref

Example One: acquiring information input box in place of e.target.value

<div>
          <Label htmlFor = 'addService'> Project Title </ label>
          <input 
                id='addService' 
                ref={(input)=>{this.input=input}}
                className='input' 
                value={this.state.inputValue} 
                onChange={this.inputChange.bind(this)} /> 
         <button onClick={this.addItem.bind(this)}> 添加项目</button>
</div> inputChange (e) { console.log(e.target.value); the this .setState ({ // for inputValue: // e.target.value first writing for inputValue: the this .input.value // REF wording }) }

Example Two: Get the document all the elements of a DOM node

<ul ref={(ul)=>{this.ul = ul}}>
        {
            this.state.list.map((item,index)=>{
                  return (
                     <Item content={item} 
                           key={index+item}
                           index={index}
                           deleteItem={this.deleteItem.bind(this)}
                             />
                    )
             })
      }
 </ ul> 
 addItem () { 
// this.setState is loaded asynchronously, after ul li below the dynamic loading, need to count all the elements with this.setState callback function to go
the this .setState ({ list: [...this.state.list,this.state.inputValue], inputValue: '' },()=>{ console.log(this.ul.querySelectorAll('li').length,'1111') }) console.log ( the this .ul.querySelectorAll ( 'li'). length, '2222' ) // this prints the wrong data, you need to print the callback function in this.setState }

 

Guess you like

Origin www.cnblogs.com/linjiu0505/p/11889455.html