react 獲取input 輸入框的值的多種方式
- 第一種方式 非受控組件獲取
- 第二種方式 受控組件獲取
非受控組件獲取 ref
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import React , {Component} from 'react' ; export default class App extends Component{ search(){ const inpVal = this .input.value; console.log(inpVal); } render(){ return ( <div> <input type= "text" ref={input => this .input = input} defaultValue= "Hello" /> <button onClick={ this .search.bind( this )}></button> </div> ) } } |
使用defaultValue表示組件的默認狀態,此時它只會被渲染一次,后續的渲染不起作用;input的值不隨外部的改變而改變,由自己狀態改變。
受控組件 this.setState({})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
import React , {Component} from 'react' ; export default class App extends Component{ constructor(props){ super (props); this .state = { inpValu: '' } } handelChange(e){ this .setState({ inpValu:e.target.value }) } render(){ return ( <div> <input type= "text" onChange={ this .handelChange.bind( this )} defaultValue={ this .state.inpValu}/> </div> ) } } |
input 輸入框的值會隨著用戶輸入的改變而改變,onChange通過對象e拿到改變之后的狀態并更新state,setState根據新的狀態觸發視圖渲染,完成更新。
到此這篇關于react獲取input輸入框的值的方法示例的文章就介紹到這了,更多相關react獲取input輸入框的值內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/Shuiercc/article/details/81383679