I am trying to access a state variable using a string within a React functional component.
For example, I know in Class components I can do the following to access state based on input:
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
inputOne: null
}}
handleBlur(e, name) {
if (!this.state[name]) {
this.setState({
[`${name}Missing`]: true,
});
} else {
this.setState({
[`${name}Missing`]: false,
});
}
render() {
<input onBlur={(e) => this.handleBlur(e, "inputOne")}></input>
}
}
By using this.state[name]
within the handleBlur
function, I can access the inputOne state value dynamically.
How would I do something similar within a functional component?
Thanks for your time!
The only way to do this in a functional component would be to have the same sort of state structure as in the class component - that is, for the state values you want to dynamically access, put them all into an object (or an array).
const [inputs, setInputs] = useState({
inputOne: null
})
And then const someStr = 'inputOne'
and inputs[someString]
will give you that state value. To set it:
setInputs({
...inputs,
[someStr]: newValue
// or use whatever computed property name you want
});
It's usually recommended to use separate state variables when using functional components - but when you have lots of state variables that you want to dynamically access, using a single object or array can make more sense.
You can do that:
import { useState } from 'react';
const Custom = () => {
const [state, setState] = useState({
inputOne: "",
});
const handleBlur = (e, name) => {
if (!state[name]) {
setState({
[`${name}Missing`]: true,
});
} else {
setState({
[`${name}Missing`]: false,
});
}
}
return (
<input onBlur={(e) => handleBlur(e, "inputOne")}></input>
);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.