admin管理员组

文章数量:1332395

I am trying to loop through multiple ponents in React. Essentially I would like the questions to loop through and transition similarly to the example for Lapsed User on /.

Here is the main page that the ponents will loop in:

import React from 'react';
import Q1Name from './questions/Q1Name';
import Q2Birthday from './questions/Q2Birthday';
import Q3City from './questions/Q3City';
import Q4YouReady from './questions/Q4YouReady';
import Q5Setting from './questions/Q5Setting';
import Q6Length from './questions/Q6Length';
import Q7Email from './questions/Q7Email';



class SignUpPage extends React.Component {
    render() {
        const questions = [Q1Name, Q2Birthday, Q3City, Q4YouReady, Q5Setting, Q6Length, Q7Email];
        const QList = questions.map(function(question){
            return {question};
        });
        return (
            <div className = "container-fluid">
                <div className = "question-box">
                    <Q1Name />
                </div>
            </div>
        );
    }
}

export default SignUpPage;

The below is an example ponent I would like to bring in - note each question is slightly different. They take in name, email (with validation), city, birthday (date form), and various button answer options.

import React from 'react';

class Q1Name extends React.Component {
    render() {
        return (
            <div className="questions">
                <h1 id="question-h1">What is your name?</h1>
                <form>
                    <div className="form-group">
                        <input type="name" className="form-control text-form custom-form" id="yourNameHere" aria-describedby="name" placeholder="" />
                    </div>
                    <button type="submit" className="btn btn-custom btn-lg" onClick={console.log("hallo")}>Next Question!</button>
                </form>
            </div>
        );
    }
}

export default Q1Name;

I have been able to get everything else working except for this part. Any help would be greatly appreciated!!

I am trying to loop through multiple ponents in React. Essentially I would like the questions to loop through and transition similarly to the example for Lapsed User on https://iteratehq./.

Here is the main page that the ponents will loop in:

import React from 'react';
import Q1Name from './questions/Q1Name';
import Q2Birthday from './questions/Q2Birthday';
import Q3City from './questions/Q3City';
import Q4YouReady from './questions/Q4YouReady';
import Q5Setting from './questions/Q5Setting';
import Q6Length from './questions/Q6Length';
import Q7Email from './questions/Q7Email';



class SignUpPage extends React.Component {
    render() {
        const questions = [Q1Name, Q2Birthday, Q3City, Q4YouReady, Q5Setting, Q6Length, Q7Email];
        const QList = questions.map(function(question){
            return {question};
        });
        return (
            <div className = "container-fluid">
                <div className = "question-box">
                    <Q1Name />
                </div>
            </div>
        );
    }
}

export default SignUpPage;

The below is an example ponent I would like to bring in - note each question is slightly different. They take in name, email (with validation), city, birthday (date form), and various button answer options.

import React from 'react';

class Q1Name extends React.Component {
    render() {
        return (
            <div className="questions">
                <h1 id="question-h1">What is your name?</h1>
                <form>
                    <div className="form-group">
                        <input type="name" className="form-control text-form custom-form" id="yourNameHere" aria-describedby="name" placeholder="" />
                    </div>
                    <button type="submit" className="btn btn-custom btn-lg" onClick={console.log("hallo")}>Next Question!</button>
                </form>
            </div>
        );
    }
}

export default Q1Name;

I have been able to get everything else working except for this part. Any help would be greatly appreciated!!

Share Improve this question asked Jan 29, 2018 at 2:29 KrisKris 432 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Here is a simple demo of your requirement. The key is to just create a JSX element (<Component />) in a loop and then return the result via the render method.

class A extends React.Component {
  render() {
    return <div>I'm A, with {this.props.testProp}</div>;
  }
}

class B extends React.Component {
  render() {
    return <div>I'm B, with {this.props.testProp}</div>;
  }
}

class App extends React.Component {
  render() {
    const ponents = [A, B];
    const ponentsToRender = ponents.map((Component, i) => (
      <Component key={i} testProp="testProp"/>
    ));
    return <div>{ponentsToRender}</div>;
  }
}
ReactDOM.render(<App />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Note the usage of a special key prop, when creating ponents in a loop. I've just used the index in the array for demo purposes, but it's remended to use something that'll always be unique to that ponent. More on that here.

React ponents are just functions. The JSX syntax is not something special, using <Component /> will pile to React.createElement(Component, null) (null because no props are being passed). The only special case are the ponents starting with lower case letter, for example <div />. These pile to React.createElement("div", null). This is true for any string you use, so be careful, <myCustomComponent /> will still pile into React.createElement("myCustomComponent", null), in turn creating a myCustomComponent DOM node, which most likely doesn't exist.

You can apply this knowledge to your case. You're already mapping through the list of your questions, all you need to change is the naming convention and render the questions:

const questions = [Q1Name, Q2Birthday, Q3City, Q4YouReady, Q5Setting, Q6Length, Q7Email];
const QList = questions.map(function(Question){
    return (<Question />);
});

Note: I like to add () around all the ponents, just to have some limits between JSX and regular JS code. I'm not sure if it's really needed in this case.

Alternatively, you can replace the return inside your current map function with:

return React.createElement(question, null);

Again, the null is for props value. If you want to pass some props, you can do that by passing an object instead of the null value. The passed object maps directly to this.props values inside the referenced question ponent. By the way, you can do the same with the above approach <Question prop1={prop1} prop2={prop2} /> will still work the same as it does with any other React ponent.

本文标签: javascriptTrying to loop through multiple components in ReactStack Overflow