方法一 利用DOM提供的Event對象的target事件屬性取值并提交
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
import React from 'react' ; class InputDemo extends React.Component{ state = { InputValue : "" , //輸入框輸入值 }; handleGetInputValue = (event) => { this .setState({ InputValue : event.target.value, }) }; handlePost = () => { const {InputValue} = this .state; console.log(InputValue, '------InputValue' ); //在此做提交操作,比如發dispatch等 }; render(){ return ( <div> <input value={ this .state.InputValue} onChange={ this .handleGetInputValue} /> <button onClick={ this .handlePost}>提交</button> </div> ) } } export default InputDemo; |
這里的<input />和<button />都是用的html的標簽,當然也可以使用Antd的<Input />和<Button />組件,里面的內容是不變的
首先在組件最上方state中定義了InputValue:"",下面<input />里寫了value={this.state.InputValue},如果去掉onChange事件,那么這時候輸入框里是什么都輸入不了的,因為
React認為所有的狀態都應該由 React 的 state 控制,只要類似于<input />、<textarea />、<select />這樣的輸入控件被設置了value值,那么它們的值永遠以被設置的值為準。如果值沒被改變,value就不會變化
React中要用setState才能更新組件的內容,所以需要監聽輸入框的onChange事件,獲取到輸入框的內容后通過setState的方式更新state的InputValue,這樣<input />的內容才會實時更新
再說onChange的handleGetInputValue方法,利用了DOM的Event對象的target事件屬性:
target 事件屬性可返回事件的目標節點(觸發該事件的節點),如生成事件的元素、文檔或窗口
詳情可見W3C標準介紹
方法二 利用React的ref訪問DOM元素取值并提交
無狀態組件寫法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
const InputDemo = () => { let inputValue; const handlePost = (e) => { if (e) e.preventDefault(); const valueTemp = inputValue.value; console.log(valueTemp, '------valueTemp' ); //在此做提交操作,比如發dispatch等 }; return ( <div> <form onSubmit={handlePost}> <input ref={input => inputValue = input} /> <button onClick={handlePost}>提交</button> </form> </div> ) }; export default InputDemo; |
有狀態組件寫法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
import React from 'react' ; class InputDemo extends React.Component { handlePost = (e) => { if (e) e.preventDefault(); const valueTemp = this .inputValue.value; console.log(valueTemp, '------valueTemp' ); //在此做提交操作,比如發dispatch等 }; render() { return ( <div> <form onSubmit={ this .handlePost}> <input ref={input => this .inputValue = input} /> <button onClick={ this .handlePost}>提交</button> </form> </div> ) } }; export default InputDemo; |
Ref 是 React 提供給我們的安全訪問 DOM 元素或者某個組件實例的句柄。我們可以為元素添加 ref 屬性,然后在回調函數中接受該元素在 DOM 樹中的句柄,該值會作為回調函數的第一個參數返回。
除了這兩種寫法,還可以利用Antd的Form組件實現表單功能,傳送門:React利用Antd的Form組件實現表單功能
總結
到此這篇關于React獲取input值并提交的2種方法的文章就介紹到這了,更多相關React獲取input值并提交內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/GuanJdoJ/article/details/83375570