如何映射SetState函数?

时间:2020-02-25 08:40:45

标签: javascript reactjs typescript mapping material-ui

如何映射setState函数?

这是我的setState函数示例:

const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');

这是我的映射技术:


  {[{ label: "First Name", state: 'firstName' , function: 'setFirstName'},
                  { label: "Last Name", state: 'lastName' },
                  { label: "Email", state: 'email' },
                  { label: "Password", state: 'password' },
                  { label: "Phone", state: 'phone' }].map((item, index) => (
                    <div>
                      <TextField
                        id="outlined-basic"
                        key={index}
                        label={item.label}
                        variant="outlined"
                        onChange= {e => setFirstName(e.target.value)}          
                      />
                      <br></br><br></br>
                    </div>
                  )
  )}

这可行,但是我想以这样的方式更改onChange,而不是setFirstName,我可以传入该函数并映射所有它们(例如firstName,lastName等)。我该如何解决?

2 个答案:

答案 0 :(得分:4)

只需删除statefunction的引号,并在function内使用onChange


    [
      { label: 'first name', state: firstName, function: setFirstName },
      { label: 'last name', state: lastName, function: setLastName },
    ].map((item, index) => (
      <TextField
        key={index}
        label={item.label}
        onChange={e => item.function(e.target.value)} // use state function       
      />
    ))

答案 1 :(得分:0)

我将使用一个对象来跟踪表单的状态,但这是我映射不同的设置状态操作的方式。

const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');

const textFields = [
  {
    label: 'First name',
    onChange: handleChange(setFirstName),
    value: firstName
  },
  {
    label: 'Last name',
    onChange: handleChange(setLastName),
    value: lastName
  }
];

const handleChange = setStateAction => ({ target }) => {
  setStateAction(target.value);
}

return textFields.map((props, index) => (
  <TextField key={index} {...props} />
));