React es una biblioteca de JavaScript utilizada para desarrollar interfaces de usuario interactivas. Es administrado por Facebook y una comunidad de desarrolladores individuales y empresas. React se enfoca principalmente en desarrollar aplicaciones web o móviles de una sola página. aquí, crearemos una aplicación de prueba para comprender los conceptos básicos de reactjs.
Módulos requeridos:
- npm
- Reaccionar
- Reaccionar Bootstrap
npm install react-bootstrap bootstrap
Configuración básica:
Inicie un proyecto con el siguiente comando:
npx create-react-app quiz
NPX es una herramienta de ejecución de paquetes que viene con npm 5.2+, npx es una herramienta CLI fácil de usar. npx se usa para ejecutar paquetes de Node. Simplifica en gran medida una serie de cosas, una de las cuales es verificar/ejecutar un paquete de Node rápidamente sin instalarlo local o globalmente.
ahora ve a la carpeta crear
cd quiz
Inicie el servidor: inicie el servidor escribiendo el siguiente comando en la terminal:
npm start
abre http://localhost:3000/
Cambiar directorio a src –
cd src
Eliminar todo dentro del directorio.
rm *
Ahora crea index.js
archivos
touch index.js
Este archivo representará nuestra aplicación en un archivo html que ahora se encuentra en una carpeta pública , cree un componente de nombre de carpeta con los archivos src/components/QuestionBox.js y src/components/ResultBox.js para contener los componentes de nuestra aplicación y una pregunta de carpeta con el archivo src /question/index.js para guardar nuestras preguntas.
mkdir components && cd components && touch app.js
mkdir question && cd question && index.js
Edite el archivo src/index.js.
Este archivo contiene la lógica de nuestra aplicación.
import React, {Component} from "react"; import ReactDOM from "react-dom"; import "./style.css"; import questionAPI from './question'; import QuestionBox from './components/QuestionBox'; import Result from './components/ResultBox'; class Quiz extends Component { constructor() { super(); this.state = { questionBank: [], score: 0, responses: 0 }; } // Function to get question from ./question getQuestions = () => { questionAPI().then(question => { this.setState({questionBank: question}); }); }; // Set state back to default and call function playAgain = () => { this.getQuestions(); this.setState({score: 0, responses: 0}); }; // Function to compute scores computeAnswer = (answer, correctAns) => { if (answer === correctAns) { this.setState({ score: this.state.score + 1 }); } this.setState({ responses: this.state.responses < 5 ? this.state.responses + 1 : 5 }); }; // componentDidMount function to get question componentDidMount() { this.getQuestions(); } render() { return (<div className="container"> <div className="title"> QuizOn </div> {this.state.questionBank.length > 0 && this.state.responses < 5 && this.state.questionBank.map(({question, answers, correct, questionId}) => <QuestionBox question= {question} options={answers} key={questionId} selected={answer => this.computeAnswer(answer, correct)}/>)} { this.state.responses === 5 ? (<Result score={this.state.score} playAgain={this.playAgain}/>) : null } </div>) } } ReactDOM.render(<Quiz/>, document.getElementById("root"));
Edite el archivo src/question/index.js: este archivo contiene todas las preguntas que se mostrarán.
const qBank = [ { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "099099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "093909" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "009039" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "090089" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "01010101" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "092299" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "099099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "222099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "2222099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "09922099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "222292099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "0998999099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "099099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "099099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "099099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "09459099" }, { question: "how build the app ?", answers: ["vinayak", "sarthak", "somil", "devesh"], correct: "vinayak", questionId: "0912219099" }, ]; // n = 5 to export 5 question export default (n = 5) => Promise.resolve(qBank.sort(() => 0.5 - Math.random()).slice(0, n));
Edite el archivo src/components/QuestionBox.js: este archivo crea un cuadro de preguntas con botones.
import React, {useState} from "react"; import "../style.css"; // Function to question inside our app const QuestionBox = ({ question, options, selected}) => { const [answer, setAnswer] = useState(options); return ( <div className="questionBox"> <div className="question">{question}</div> {answer.map((text, index) => ( <button key={index} className="answerBtn" onClick={()=>{ setAnswer(); selected(text); }}> {text} </button> ))} </div> ) }; export default QuestionBox;
Edite el archivo src/components/ResultBox.js: este archivo muestra el resultado.
import React from 'react'; import "../style.css"; const Result = ({score, playAgain}) => ( <div className="score-board"> <div className="score"> Your score is {score} / 5 correct answer ! ! ! </div> <button className="playBtn" onClick={playAgain} > Play Again </button> </div> ) export default Result;
Guarde todos los archivos e inicie el servidor:
npm start
abra http://localhost:3000/ URL en el navegador. Mostrará el resultado.
Publicación traducida automáticamente
Artículo escrito por itsvinayak y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA