在渲染函数中调用函数-ReactJS?

时间:2018-07-02 20:17:41

标签: javascript reactjs

好,所以我正在制作“ buzzfeed”测验生成器,但是我的表单存在问题。因此,对于每个提出的问题,都有两个不同的部分,即“问题”和“答案”。总会有4个答案,但是我想跟踪以后再检查哪个答案,所以我想给每个答案一个唯一的ID "question" + questionNum + "Answer" + answerNum"question" + questionNum + "Answer" + i,所以我做了这个answersGenerator函数这应该为我提供4个唯一的答案选择填充项,以便用户输入特定问题的答案(现在它说了一些有关条款和条件的信息-忽略了我的广告,因为我正在关注教程)。这是我的所有代码:

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

var questionNum = 1;
var answerNum = 1;

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      quizTitle: "",
      author: "",
      question: "",
      terms: false,
      test: "",
    };

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

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

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

  handleSubmit(event) {
    event.preventDefault();
    console.log(this.state);
  }

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

        <div className="container">
          <div className="columns">
            <div className="formDiv">
              <form className="form" onSubmit={this.handleSubmit}>
                <div className="field">
                  <label className="label">Give your quiz a title.</label>
                  <div className="control">
                    <input
                      className="input"
                      type="text"
                      name="quizTitle"
                      value={this.state.quizTitle}
                      onChange={this.handleChange}
                    />
                  </div>
                </div>

                <div className="field">
                  <label className="label">Who's the Author?</label>
                  <div className="control">
                    <input
                      className="input"
                      type="text"
                      name="author"
                      value={this.state.author}
                      onChange={this.handleChange}
                    />
                  </div>
                </div>

                <div className="questions" id="questions">
                  <div className="question" id={'questionGroup' + questionNum}>
                    <div className="field">
                      <label className="label" id={'question' + questionNum}>Question {questionNum}</label>
                      <div className="control">
                        <input
                          className="input"
                          type="text"
                          name='question'
                          value={this.state.question}
                          onChange={this.handleChange}
                        />
                      </div>
                    </div>

                    <div className="answersDiv">
                    <label className="label">Answers</label>
                      <div className="field">
                        <div className="control">
                          <label className="checkbox">
                              {this.answersGenerator()}
                          </label>
                        </div>
                      </div>
                    </div>

                </div>
              </div>
              <div className="field">
                  <div className="endButtons">
                    <button id="addQuestionButton"
                      onClick={addQuestion}>Add Question</button>
                    <input
                      type="submit"
                      value="Submit"
                      id="submitButton"
                      className="button is-primary"
                    />
                  </div>
              </div>
              </form>
          </div>

            <div className="column is-3">
              <pre>
                <code>
                  <p>Quiz Title: {this.state.quizTitle}</p>
                  <p>Author: {this.state.author}</p>
                  <p>Question: {this.state.question}</p>
                  <p>Terms and Condition: {this.state.terms}</p>
                  <p>Do you test?: {this.state.test}</p>
                </code>
              </pre>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

function answersGenerator () {

  console.log("hello this is answer generator");
  var div = document.createElement('div');
  div.className = 'answers' + {questionNum};

  for (var i = 1; i < 5; i++){

    div.innerHTML = 
      '<div className="field">\
      <div className="control">\
        <label className="checkbox">\
        <label className="label">Answers</label>\
            <input\
              name="terms"\
              type="checkbox"\
              id="question'+{questionNum}+'Answer'+{i}+'"\
              checked={this.state.terms}\
              onChange={this.handleChange}\
            />\
            I agree to the{" "}\
            <a href="https://google.com">terms and conditions</a>\
        </label>\
      </div>';
    document.getElementsByClassName('answersDiv')[0].appendChild(div)
  }
}


function addQuestion () {
  questionNum++;
  console.log(questionNum + "that is the question number");

  var div = document.createElement('div');

    div.className = "questions" + questionNum;

    div.innerHTML =
        '<div id="questionGroup'+{questionNum}+'">\
        Question '+{questionNum}+'<br />\
        <input type="text" name="question'+{questionNum}+'"/><br />\
        Answers<br />\
        Check the box(es) for the correct answer(s).<br />\
        <input type="checkbox" name="question'+{questionNum}+'Answer1Box" />\
        <label for="question'+{questionNum}+'Answer1"><input type="text" name="question'+{questionNum}+'Answer1"/></label><br />\
        <input type="checkbox" name="question'+{questionNum}+'Answer2Box" id= />\
        <label for="question'+{questionNum}+'Answer2"><input type="text" name="question'+{questionNum}+'Answer2"/></label><br />\
        <input type="checkbox" name="question'+{questionNum}+'Answer3Box"  />\
        <label for="question'+{questionNum}+'Answer3"><input type="text" name="question'+{questionNum}+'Answer3"/></label><br />\
        <input type="checkbox" name="question'+{questionNum}+'Answer4Box"  />\
        <label for="question'+{questionNum}+'Answer4"><input type="text" name="question'+{questionNum}+'Answer4"/></label><br />\
        </div>';

      document.getElementsByClassName('questions')[0].appendChild(div)


}


export default App;

这里有些事情要忽略,我不确定您需要多少信息。因此,问题在于,当我在answersGenerator函数中调用render函数时出现错误。这是错误Uncaught TypeError: this.answersGenerator is not a function,这是小片段

            <div className="answersDiv">
            <label className="label">Answers</label>
              <div className="field">
                <div className="control">
                  <label className="checkbox">
                      {this.answersGenerator()}
                  </label>
                </div>
              </div>
            </div>

我非常感谢您的帮助,如果您有其他建议,而不是其他问题,我将不胜枚举。我现在是 非常 ,是js和React。

更新:我已经将answersDiv编辑为这样(我认为它是在复选框内被调用的)

        <div className="answersDiv">
        <label className="label">Answers</label>

                  {answersGenerator()}

        </div>

虽然我仍然遇到相同的错误。

2 个答案:

答案 0 :(得分:0)

乍一看,您似乎尚未在while IFS= read -r db do printf 'Processing: %q\n' "$db" LC_ALL=C sed -n '/^-- Current Database: `'"$db"'`/,/^-- Current Database: `/p' mysqldump.sql > "$db.sql" done < file_with_databasesnames.txt 类中定义answersGenerator()函数。

因此,App不存在。

尝试仅使用this.answersGenerator()而不使用answersGenerator()

答案 1 :(得分:0)

由于answersGenerator()不是类App的方法,所以您收到错误,因此,您不能使用this来引用它。如果您想这样做,请将函数移至组件内部,如下所示:

class App extends Component {
    // your component definition etc..
    answersGenerator = () => {
        // your function implementation
    }
    // the rest of your component
}

提示:

如果您不想总是绑定该函数,例如:

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

像这样声明您的方法:

handleChange = (event) => { // the implementation }

代替

handleChange(event) { // the implementation }

() => {}(称为arrow function)为您执行绑定。

编辑

您正在使用React开发,它支持在代码内部创建HTML。因此,您可以创建一个答案数组,然后返回一个div并将答案映射到内部。 map将采用每个answer并在div内部进行渲染。尝试如下定义您的方法:

answersGenerator => () {
    console.log("hello this is answer generator");
    var answers = []
    for (var i = 1; i < 5; i++){
      answers.push(
        <div className="field">
          <div className="control">
            <label className="checkbox">
               <label className="label">Answers</label>
               <input
                 name="terms"
                 type="checkbox"
                 id=`question${questionNum}Answer${i}`
                 checked={this.state.terms} 
                 onChange={this.handleChange}
               />
               I agree to the{" "}
               <a href="https://google.com">terms and conditions</a>
           </label>
         </div>
       );
    } 
    return <div className=`answer${questionNum}`> {answers.map(answer => answer)} </div>
}