javascript - 动态添加按钮到div ReactJS?

标签 javascript reactjs

好的,这是我的代码:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

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);
    this.removeItem = this.removeItem.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
    });
  }

  removeItem (index) {
    questionNum--;
    this.setState(({ questions }) => {
      const mQuestions = [ ...questions ]
      mQuestions.splice(index, 1)
      return { questions: mQuestions }
    })
    this.setState(({ answers }) => {
      const mAnswers = [ ...answers]
      mAnswers.splice(index, 4)
      return { answers: mAnswers}
    })
    console.log(
      "answers",
      this.state.answers,
      "questions",
      this.state.questions,
      questionNum,
      this.state.title,
      this.state.author
    );
  }

  addQuestion() {
    questionNum++;
    this.setState(previousState => {
      const questions = [
                          ...previousState.questions,
                          <input 
                            type="text"
                            onChange={this.handleChange}
                            name="question"
                            key={uuid()}
                          />
                        ];
      const answers = [
                        ...previousState.answers,
                      ];

      for (var i = 0; i < 4; i++) {
        answers.push(
          <input 
          type="checkbox" 
          name={uuid()}>
                <input 
                 type="text"
                 onChange={this.handleChange}
                 name={uuid()}
                />
          </input>
        );
      }
      return { questions, answers };
    });
    console.log(
      "answers",
      this.state.answers,
      "questions",
      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 3.0</h1>
          </header>
          <p className="App-intro">
            To get started, edit <code>src/App.js</code> and save to reload.
          </p>
        </div>

        <div  className="formDiv">
          <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">
            <div className="questions">
              Now let's add some questions... <br />
              <ol>
              {this.state.questions.map(question => {
                return (
                  <li>
                  <div key={uuid()}>
                    Question
                    {question}<br />
                    Answer Choices<br />
                    {Array.from({ length: 4 }, () => (
                      <input type="text" key={uuid()} onChange={this.handleChange} />
                    ))}
                  </div>
                  </li>
                );
              })}
              </ol>
            </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 id="addQuestionButton" onClick={this.addQuestion}>Add Question</button>
          { this.state.questions.map((question, index) => {
          return <button key={uuid()} onClick={ () => this.removeItem(index) }>Remove Question</button>
        }) }
        </div>
      </div>
    );
  }
}

export default App;

好的,那么here's a link一个简短的视频展示了它目前的作用。在视频中,您可以看到每次添加问题时都会创建的Remove Question 按钮(位于表单底部)。我希望每个问题的 Remove Question 按钮位于其旁边/同一 div 中。我不完全确定我将如何去做这件事。有什么想法吗?

更新:好吧,我已经将按钮放在与实际问题相同的 div 中,但我意识到我正在为数组中的每个对象添加一个按钮。这意味着当添加问题时,表单上的每个问题都会添加一个用于删除该问题的按钮。我需要使它不 .map 这个。我不完全确定我会为此执行什么其他功能,也许我什至不需要功能。我会尽力解决它。这是更新后的代码(其中一些):

<div className="questions">
              Now let's add some questions... <br />
              <ol>
              {this.state.questions.map(question => {
                return (
                  <li>
                  <div key={uuid()}>
                    Question
                    {question}<br />
                    {
                      this.state.questions.map((question, index) => {
                        return <button key={uuid()} onClick={ () => this.removeItem(index) }>Remove Question</button>
                      }) 
                    }
                    Answer Choices<br />
                    {Array.from({ length: 4 }, () => (
                      <div>
                        <input type="checkbox" />
                        <input type="text" key={uuid()} onChange={this.handleChange} />
                      </div>
                    ))}
                  </div>
                  </li>
                );
              })}
              </ol>

            </div>

最佳答案

类似这样的事情...

        <ol>
          {this.state.questions.map((question, index) => {
            return (
              <li>
              <div key={uuid()}>
                Question
                {question}<br />
                <button onClick={ () => this.removeItem(index) }>
                  Remove Question
                </button>
                Answer Choices<br />
                {Array.from({ length: 4 }, () => (
                  <div key={uuid()}>
                    <input type="checkbox" />
                    <input type="text" onChange={this.handleChange} />
                  </div>
                ))}
              </div>
              </li>
            );
          })}
        </ol>

关于javascript - 动态添加按钮到div ReactJS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51293604/

相关文章:

javascript - 下一个JS : Loading Font from Database

javascript - 表单提交连接到 js 事件不起作用

javascript - ExtJS:返回 json 存储中的总行/记录

javascript - 如何提供解耦的 React 前端?

reactjs - 样式化组件 : shared styled components when using <S. Name/> 命名约定

React.js:使用相同的表单进行添加和更新

javascript - 使用react-apollo进行服务器端渲染

javascript - 设置单选按钮在单击文本区域时选中

javascript - 如何从 Express.js 的动态辅助函数中访问 res.render() 中设置的变量?

javascript - 如何在reactjs中的if语句中检查多个状态?