方法一 利用DOM提供的Event對(duì)象的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' ); //在此做提交操作,比如發(fā)dispatch等 }; render(){ return ( <div> <input value={ this .state.InputValue} onChange={ this .handleGetInputValue} /> <button onClick={ this .handlePost}>提交</button> </div> ) } } export default InputDemo; |
這里的<input />和<button />都是用的html的標(biāo)簽,當(dāng)然也可以使用Antd的<Input />和<Button />組件,里面的內(nèi)容是不變的
首先在組件最上方state中定義了InputValue:"",下面<input />里寫了value={this.state.InputValue},如果去掉onChange事件,那么這時(shí)候輸入框里是什么都輸入不了的,因?yàn)?/p>
React認(rèn)為所有的狀態(tài)都應(yīng)該由 React 的 state 控制,只要類似于<input />、<textarea />、<select />這樣的輸入控件被設(shè)置了value值,那么它們的值永遠(yuǎn)以被設(shè)置的值為準(zhǔn)。如果值沒被改變,value就不會(huì)變化
React中要用setState才能更新組件的內(nèi)容,所以需要監(jiān)聽輸入框的onChange事件,獲取到輸入框的內(nèi)容后通過setState的方式更新state的InputValue,這樣<input />的內(nèi)容才會(huì)實(shí)時(shí)更新
再說onChange的handleGetInputValue方法,利用了DOM的Event對(duì)象的target事件屬性:
target 事件屬性可返回事件的目標(biāo)節(jié)點(diǎn)(觸發(fā)該事件的節(jié)點(diǎn)),如生成事件的元素、文檔或窗口
詳情可見W3C標(biāo)準(zhǔn)介紹
方法二 利用React的ref訪問DOM元素取值并提交
無(wú)狀態(tài)組件寫法:
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' ); //在此做提交操作,比如發(fā)dispatch等 }; return ( <div> <form onSubmit={handlePost}> <input ref={input => inputValue = input} /> <button onClick={handlePost}>提交</button> </form> </div> ) }; export default InputDemo; |
有狀態(tài)組件寫法:
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' ); //在此做提交操作,比如發(fā)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 元素或者某個(gè)組件實(shí)例的句柄。我們可以為元素添加 ref 屬性,然后在回調(diào)函數(shù)中接受該元素在 DOM 樹中的句柄,該值會(huì)作為回調(diào)函數(shù)的第一個(gè)參數(shù)返回。
除了這兩種寫法,還可以利用Antd的Form組件實(shí)現(xiàn)表單功能,傳送門:React利用Antd的Form組件實(shí)現(xiàn)表單功能
總結(jié)
到此這篇關(guān)于React獲取input值并提交的2種方法的文章就介紹到這了,更多相關(guān)React獲取input值并提交內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/GuanJdoJ/article/details/83375570