【发布时间】:2021-08-06 07:37:33
【问题描述】:
我正在根据文本框传递给事件处理程序的 onchange 事件更新初始状态,如下所示 -
import React,{useState} from 'react'
function ViewAll() {
const iCandidateState={
Name:'',
Age:'',
Qalification:''
};
function nameHandler(event){
alert(event.target.value);
this.iCandidateState.Name=event.target.value;
}
return (
<div>
<table>
<tr>
<td>
Name
</td>
<td>
<input type="text" name="txtName" value={iCandidateState.Name} onChange={(e)=>nameHandler(e)}></input>
</td>
</tr>
<tr>
<td>
Age
</td>
<td>
<input type="text" name="txtAge"></input>
</td>
</tr>
<tr>
<td>
Qalification
</td>
<td>
<input type="text" name="txtQualification"></input>
</td>
</tr>
<tr>
<td colSpan="2" align="center">
<button name="btnSubmitForm">Post</button>
</td>
</tr>
</table>
</div>
)
}
export default ViewAll
当我在 txtName 中输入内容时,我希望 state - iCandidateState 能够使用文本框中的 Name 字段进行更新。但我收到一个错误 - TypeError: Cannot read property 'iCandidateState' of undefined
我也试过用 setState as -
this.setState({
...iCandidateState,
Name:event.target.value
})
在文本框中输入内容后,我收到错误 -
TypeError: Cannot read property 'setState' of undefined
如何更新状态?
【问题讨论】:
标签: javascript reactjs react-redux state