javascript - 从数组 React 中删除项目?

标签 javascript reactjs

我正在制作一个允许用户构建测验的表单(到目前为止,这是我的代码)

var uuid = require("uuid-v4");
// Generate a new UUID
var myUUID = uuid();
// Validate a UUID as proper V4 format
uuid.isUUID(myUUID); // true

var questionNum = 0;

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      key: uuid(),
      title: "",
      author: "",
      questions: [],
      answers: []
    };

    this.handleChange = this.handleChange.bind(this);
    this.addQuestion = this.addQuestion.bind(this);
  }

  componentDidMount() {
    // componentDidMount() is a React lifecycle method
    this.addQuestion();
  }

  handleChange(event) {
    const target = event.target;
    const value = target.type === "checkbox" ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  /**
   * It's probably better to structure your questions like this:
   * this.state.questions: [{
   *         question: 'How are you?',
   *         answers: ['Good', 'Great', 'Awful'],
   *         // correctAnswer: 'Great'
   *     },
   *     {
   *         question: 'What is your name?',
   *         answers: ['Toby', 'Marco', 'Jeff'],
   *         // correctAnswer: 'Jeff'
   *     }];
   *
   * This allows you to keep better track of what questions
   * have what answers. If you're making a 'quiz' type structure,
   * you could additionally add a `correctAnswer` property.
   */

  addQuestion() {
    questionNum++;
    this.setState(previousState => {
      const questions = [...previousState.questions, "question", "hi"];
      const answers = [...previousState.answers];

      for (var i = 0; i < 4; i++) {
        answers.push({
          answerChoice: "",
          key: uuid()
        });
      }
      return { questions, answers };
    });
    console.log(
      this.state.answers,
      this.state.questions,
      questionNum,
      this.state.title,
      this.state.author
    );
  }

  render() {
    return (
      <div className="App">
        <div>
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <h1 className="App-title">Quiz Form 2.0</h1>
          </header>
          <p className="App-intro">
            To get started, edit <code>src/App.js</code> and save to reload.
          </p>
        </div>

        <div>
          <form>
            <div className="Intro">
              Give your Quiz a title:{" "}
              <input
                type="text"
                value={this.state.title}
                onChange={this.handleChange}
                name="title"
              />
              <br />
              Who's the Author?{" "}
              <input
                type="text"
                value={this.state.author}
                onChange={this.handleChange}
                name="author"
              />
              <br />
              <br />
            </div>
            <div className="questions">
              Now let's add some questions... <br />
              {// This is where we loop through our questions to
              // add them to the DOM.
              this.state.questions.map(question => {
                return <div>{question}</div>;
              })

              // This is what it would look like for the structure
              // I proposed earlier.
              // this.state.questions.map((question) {
              //   return (
              //       <div>{question.quesion}</div>
              //       {
              //           question.answers.map((answer) => {
              //               return (<div>{answer}</div>);
              //           })
              //       }
              //   );
              // })
              // This would output all questions and answers.
              }
            </div>
          </form>
          <button onClick={this.addQuestion}>Add Question</button>
        </div>
      </div>
    );
  }
}

export default App;

我已经到了想要尝试并能够“删除”问题(使用按钮)的地步。我的代码现在所做的是将对象添加到数组中,我已经弄明白了。但现在我正试图从数组中删除项目。我在想“好吧,只删除最后一个问题”,但实际上用户会想要删除他们的任何问题。我只是很好奇是否有人对此有一些提示,我真的不知道如何开始。

最佳答案

如果您希望用户能够删除任何问题,请将 onClick 添加到问题 div(或 div 的子级 - 记住移动 点击)。它的回调可以接受一个索引,它指的是列表中要删除的元素。

例子:

class App extends Component {
  constructor(props) {
    super(props)

    this.removeItem = this.removeItem.bind(this)
  }

  removeItem (index) {
    this.setState(({ questions }) => {
      const mQuestions = [ ...questions ]
      mQuestions.splice(index, 1)
      return { questions: mQuestions }
    })
  }

  render () {
    return (
      <div>
        ...
        { this.state.questions.map((question, index) => {
          return <div onClick={ () => this.removeItem(index) }>{ question }</div>
        }) }
      </div>
    )
  }
}

关于javascript - 从数组 React 中删除项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51273357/

相关文章:

reactjs - react 钩子(Hook)中的prevstate

javascript - 找不到变量 : StyleSheet

javascript - Framer API Scroll 组件水平滚动 - React

javascript - 调用函数作为 Enzyme 中的 prop 传递

javascript - 通过单击选项卡而不是单击网站的任何部分来隐藏选项卡

javascript - Parse.Query 和组合问题

javascript - 通过链接使用发布请求导航到另一个页面

javascript - 将包含函数的变量从 pug 传递到 react 组件

javascript - 在 Google Map API V3 中显示特定信息窗口

JavaScript - 构造函数中的继承