首页 > 解决方案 > 获取点击的对象并填写 ReactJS 中的输入

问题描述

我想要实现的是能够获取添加的下一个对象的所有新数据,还能够单击打印的 div 并获取当前对象进行编辑。我已经构建了一些东西,但是缺少关键逻辑。

问题:

  1. 显示当前输入字段
  2. 能够切换到 div(对象)并获取输入中的值,以便我可以编辑
import { useState, useEffect } from 'react';

export default function AddQuiz() {
  const [current, setCurrent] = useState(1);
  const [questions, setQuestions] = useState([]);

  function add_question() {
    const dumb = {
      id: `${Math.floor(100000 + Math.random() * 900000)}`,
      question: `${Math.random().toString(36).substr(2, 5)}`,
      anwser1: `${Math.random().toString(36).substr(2, 5)}`,
      anwser2: `${Math.random().toString(36).substr(2, 5)}`,
      anwser3: `${Math.random().toString(36).substr(2, 5)}`,
      anwser4: `${Math.random().toString(36).substr(2, 5)}`,
    };

    setQuestions([...questions, dumb]);
  }

  return (
    <>
      <pre>
        {' '}
        {questions.map((item) => (
          <div>
            question: {item.question} anwser1: {item.anwser1} anwser2: {item.anwser2} anwser3: {item.anwser3} anwser4:{' '}
            {item.anwser4}
          </div>
        ))}{' '}
      </pre>
      <button onClick={() => add_question()}>add dump question</button>

      <br />
      <br />
      <hr />

      {questions.length !== 0 ? (
        <form>
          <input type="text" value={questions[0].question} />
          <input type="text" value={questions[0].anwser1} />
          <input type="text" value={questions[0].anwser2} />
          <input type="text" value={questions[0].anwser3} />
          <input type="text" value={questions[0].anwser4} />
        </form>
      ) : (
        'please add some question'
      )}
    </>
  );
}

标签: reactjs

解决方案


onChange您需要添加input field并正确使用它。

在这里,我创建了一个您正在寻找的代码框。https://codesandbox.io/s/redux-shop-cart-forked-z891d?file=/src/App.js


推荐阅读