如何在提交按钮单击时将值推送到数组中(反应 js)

How to push values into an array on submit btn click (react js)

我有一个带有自定义输入的问题表单。

const Input = (props) => {
    return (
        <div>
            <label className={classes.label}>{props.label}
            <input className={classes.input} {...props}/>
            </label>
        </div>
    );
};

我从服务器获取问题列表并将它们设置到 questions。然后我创建了一个表格来回答这些问题。

<form onSubmit = {onAnswersSubmit}>
     {questions?.map((item) =>
         <Input key={item.id} id={item.id} label={item.question}/>)}
      <Button> Submit </Button>
</form>

我想在单击提交按钮时将输入的答案推送到数组中,但不知道该怎么做。

您可以使用 html inputonChange 道具并从您的父表单传递一个 onChange 函数来处理它,如下所示:

// This is assuming this is inside a functional component

const [answers, setAnswers] = useState([]);

const onAnswerChange = useCallback((index, answer) => {
  setAnswers((oldAnswers) => {
    oldAnswers[index] = answer;
    return oldAnswers;
  });
}, [setAnswers]);

return 
<form onSubmit = {onAnswersSubmit}>
     {questions?.map((item, index) =>
         <Input key={item.id} 
                id={item.id} 
                label={item.question}
                value={answers[index] ?? ''}
                onChange={(e) => onAnswerChange(index, evt.target.value)}/>)}
      <Button> Submit </Button>
</form>

然后您可以使用 answers 中存储的状态作为 onAnswersSubmit 回调的一部分。

您可能应该为此使用状态。数组的一种状态(我称之为 state),另一种状态用于捕获问题的答案(一个对象)。

当触发输入的 onChange 侦听器时,它会调用 handleChange。此函数从输入中获取名称和值(注意:此示例假定您可以将 name 属性 添加到从服务器接收的数据中),然后更新 answers状态。

单击按钮时,已完成的 answers 状态(一个对象)被添加到主状态数组中。

const { useEffect, useState } = React;

function Example({ data }) {

  // Initialise the states
  const [ state, setState ] = useState([]);
  const [ answers, setAnswers ] = useState({});

  // Push the completed answers object into
  // the state array, then reset the answers state
  function handleClick() {
    setState([ ...state, answers ]);
    setAnswers({});
  }

  // Get the name and value from the input
  // and update the answers state
  function handleChange(e) {
    const { name, value } = e.target;
    setAnswers({ ...answers, [name]: value });
  }

  // Log the main state when it changes
  useEffect(() => console.log(state), [state]);

  return (
    <div>
      {data.map(obj => {
        const { id, name, question } = obj;
        return (
          <input
            key={id}
            name={name}
            placeholder={question}
            onChange={handleChange}
          />
        );
      })}
      <button onClick={handleClick}>Submit</button>
    </div>
  );

}

const data = [
  { id: 1, name: 'name', question: 'What is your name?' },
  { id: 2, name: 'age', question: 'How old are you?' },
  { id: 3, name: 'location', question: 'Where do you live?' }  
];

ReactDOM.render(
  <Example data={data} />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

const [answers, setAnswers] = useState([]);

const handleAnswerChange = (index, answer) => {
    let olddata=answers;
    olddata[index]=answer;
    setAnswers([...olddata]);
}


const Input = (props) => {
    return (
        <div>
            <label className={classes.label}>{props.label}
            <input className={classes.input} {...props}/>
            </label>
        </div>
    );
};

<form onSubmit = {onAnswersSubmit}>
     {questions?.map((item) =>
         <Input key={item.id} id={item.id} label={item.question} onChange={handleAnswerChange}/>)}
      <Button> Submit </Button>
</form>