问题
this is a continuation of: How to use a handler function for two different purposes. SPFX (React/TypeScript)
which I've made a little progress from, so this isn't a duplicate, it's part 2 as it were.
My current code handler is:
const {value} = (evt.target as any);
const countKey = `${evt.target.name}Count`;
const obj = {
[evt.target.name]: value,
[countKey]: value.toString().length,
};
this.setState({
...this.state,
obj
}, () => { console.log(obj), console.log(countKey+'countKey'), console.log(value+'value');});
}
The render with the fields in question:
<td><TextField //THIS IS THE USER INPUT TEXTFIELD WHICH I WANT COUNTED BY THE TEXTFIELD BELOW!
name="EssCrit1"
value={this.state.EssCrit1}
onChange={this.handleChange}
multiline rows={2}
/>
</td>
<td ><TextField //THIS IS THE CHARACTER COUNTER FIELD!
name="EssCritChars1"
value={this.state.EssCrit1Count}
disabled={true}
/>
</td>
As you can see I'm logging obj and this is showing the correct textfield value typed in also it is counting how many characters. Problem is it doesn't allow text to be typed into the textfield. The value (EssCrit1) and the (EssCrit1Count) field seem to be registering the key press showing:
[object Object]: {EssCrit1: "h", EssCrit1Count: 1}
EssCrit1: "h"
EssCrit1Count: 1
__proto__: Object
in the console. But as mentioned it doesn't allow any text to be typed into the field. It seems as if the state is being overwritten as soon as something is typed in. Or something else which isn't apparent.
If it helps here is my state for the EssCrit1 textfield and it's accompanying character counter:
EssCrit1:null,
EssCrit1Count: null,
回答1:
Went with:
public handleChange = (evt: any) => {
const {value} = (evt.target as any);
const countKey = `${evt.target.name}Count`;
const obj = {
[evt.target.name]: value,
[countKey]: value.toString().length,
};
this.setState(prevState => ({prevState, ...obj}));
}
and for the render:
<td><TextField
name="EssCrit1"
value={this.state.EssCrit1}
onChange={this.handleChange}
multiline rows={2}
/>
</td>
<td ><TextField
name="EssCrit1Count"
value={this.state.EssCrit1Count}
disabled={true}
/>
</td>
Matched up the text 'Count' at the end of the const CountKey variable assignment from the handler with the states that required it. The main issue was the updating of the states. I changed this to
this.setState(prevState => ({prevState, ...obj}));
from
this.setState(prevState => ({...prevState, newState });
which encompasses the changes detailed in the handler. Hope this helps someone. I'm going to reverse engineer what I have learnt from the magnificent help I've received. Thank you to everyone as always.
来源:https://stackoverflow.com/questions/59664868/how-to-create-a-handler-function-which-handles-multiple-textfields-but-also-ch