javascript 在React上使用多个按钮在同一网页上导航

jum4pzuy  于 2023-01-07  发布在  Java
关注(0)|答案(4)|浏览(114)

作为一个初学者,我只是在React中闲逛。我正在尝试做一个调查问卷。我问用户是否有笔记本电脑,然后继续问关于它的问题。如果第一个问题点击了“是”按钮,下一个问题显示出来了--什么样的笔记本电脑。在这里我想以按钮的形式显示3个选项,而不是像上一个问题那样显示2个,链条继续。如果在第一个问题上单击“否”,则会显示另一个问题。我希望这些问题位于同一个网页上,而不是重定向到另一个页面。我还希望即将出现的问题按钮最初不会显示。我对HTML和JS以及React的基本原理有很好的理解。

class App extends React.Component {

  constructor() {
    super(); 
    this.state = { showMessage: false }
  }

  _showMessage = (bool) => {
    this.setState({
      showMessage: bool
    });
  }

  render() {
    return (
      <div>
        Do you have a laptop <br/>
        <button onClick={this._showMessage.bind(null, true)}>yes</button>
        <button onClick={this._showMessage.bind(null, false)}>no</button>
        { this.state.showMessage && (<div>What kind of laptop?</div>) }
        <br/>
{/* I want to hide these buttons until the 'yes' button is clicked*/}
        <button onClick={this._showMessage.bind(null, true)}>Windows</button>
        <button onClick={this._showMessage.bind(null, false)}>IOS</button>
{/* I want to display a third button which says none of the above */}
        { this.state.showMessage && (<div>when did you buy it?</div>) }
    </div> )
  }
}
9rnv2umw

9rnv2umw1#

您可以将当前步骤存储在状态中,每次单击所需按钮时增加状态,并根据步骤在页面上显示必要的内容。

const App = () => {
      const [step, setStep] = React.useState(1)

      const handleNextStep = () => setStep(prevStep => prevStep + 1)

      const handleFirstStep = () => setStep(1)

      return (
        <div>
          Do you have a laptop <br/>
          <button onClick={handleNextStep}>yes</button>
          <button onClick={handleFirstStep}>no</button>
          {step > 1 && (
            <>
              <div>What kind of laptop?</div>
              <br/>
              <button onClick={handleNextStep}>Windows</button>
              <button onClick={handleNextStep}>IOS</button>
            </>
          )}

          {step > 2 && (<div>when did you buy it?</div>)}
        </div>
      )
    }

const root = ReactDOM.createRoot(document.querySelector("#root"))
root.render(<App />)
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<body>
  <div id="#root"/>
</body>
kgsdhlau

kgsdhlau2#

不是100%确定您的问题,但似乎您有几个步骤,因此您可以切换activeStep并基于activeStep呈现必要的内容

class App extends React.Component {

  constructor() {
    super(); 
    this.state = { activeStep: 1 }
  }

  moveToNextStep = (step) => {
    this.setState({
      activeStep: step
    });
  }

  render() {
    return (
     {/* STEP 1 */}
     {this.state.activeStep === 1 && (
        <div>
          Do you have a laptop <br/>
          {/* move to step 2 */}
          <button onClick={() => this.moveToNextStep(2)}>yes</button>
          {/* move to some other step... */}
          <button onClick={() => {}}>no</button>
        </div>
      )}
      {/* STEP 2 */}
      {this.state.activeStep === 2 && (
         <div>
           What kind of laptop?<br/>
           {/* move to step 3 */}
           <button onClick={() => this.moveToNextStep(3)}>Windows</button>
           {/* move to some other step and etc.... */}
           <button onClick={() -> {}}>IOS</button>
         </div>
      )}
      {/* STEP 3 */}
      {this.state.activeStep === 3 && (
         <div>
           when did you buy it?
         </div>
      )}
  }
}
i86rm4rw

i86rm4rw3#

我对你的第二条评论有点困惑,但是对于第一条评论,你可以 Package 你的按钮,并根据一个条件呈现它们。

import React from "react";
class App extends React.Component {
  constructor() {
    super();
    this.state = { showMessage: false, os: "" };
  }

  _showMessage = (bool) => {
    this.setState({
      showMessage: bool
    });
  };

  _setOs = (value) => {
    this.setState({
      os: value
    });
  };

  render() {
    return (
      <div>
        Do you have a laptop <br />
        <button onClick={this._showMessage.bind(null, true)}>yes</button>
        <button onClick={this._showMessage.bind(null, false)}>no</button>
        {this.state.showMessage && <div>What kind of laptop?</div>}
        <br />
                // when user clicks yes, buttons will appear

        {this.state.showMessage === true && (
          <div>
            {/* I want to hide these buttons until the 'yes' button is clicked*/}
            <button onClick={this._setOs.bind(null, "Windows")}>Windows</button>
            <button onClick={this._setOs.bind(null, "IOS")}>IOS</button>
            <button onClick={this._setOs.bind(null, "")}>None</button>
          </div>
        )}
        {/* I want to display a third button which says none of the above */}

             // If use clicks windows or IOS, it will show him the next 
             //question. otherwise it wont show anything
        {!!this.state.os && <div>when did you buy it?</div>}
      </div>
    );
  }
}

export default App;

请把你的逻辑解释清楚,这样我就能理解它,并修改我的答案和完成你的问题的其余部分。

xxb16uws

xxb16uws4#

我不熟悉基于类的组件,但下面是我如何创建一个调查问卷。注意,我使用的是functional components
第一件事是创建一个对象,其中包含每个步骤的所有questionsanswers和可能的outcomes

export const QuestionsAnswers = {
  1: {
    question: "Do you have a laptop",
    answers: [
      { answer: "Yes", nextStep: 2 },
      { answer: "No", nextStep: 3 },
    ],
  },
  2: {
    question: "What kind of laptop?",
    answers: [
      { answer: "Windows", nextStep: 5 },
      { answer: "IOS", nextStep: 5 },
    ],
  },
  3: {
    question: "Do you have a desktop?",
    answers: [
      { answer: "Yes", nextStep: 4 },
      { answer: "No", nextStep: 5 },
    ],
  },
  4: {
    question: "What OS does it have?",
    answers: [
      { answer: "Windows", nextStep: 5 },
      { answer: "IOS", nextStep: 5 },
    ],
  },
  5: {
    question: "Questions Over!",
    answers: [],
  },
};

接下来,我们将创建一个组件,该组件将问题和答案对象中的一个步骤作为 prop ,它将返回问题文本并循环访问选项以供用户选择,它还将使用setState函数来设置下一步:

const Question = ({ questions, setStep }) => {
  return (
    <div>
      <p>{questions.question}</p>
      {questions.answers.map((e) => {
        return <button onClick={() => setStep(e.nextStep)}>{e.answer}</button>;
      })}
    </div>
  );
};
export default Question;

最后,在父组件中声明步骤状态并呈现Question组件。

import "./styles.css";
import React from "react";
import Question from "./Question";
import { QuestionsAnswers } from "./QuestionsAnswers";

export default function App() {
  const [step, setStep] = React.useState(1);
  return (
    <div className="App">
      <h1>Question</h1>
      <Question questions={QuestionsAnswers[step]} setStep={setStep} />
    </div>
  );
}

通过这种设置,您可以轻松地扩展/调整问题,并且您的代码将根据初始问答对象动态地呈现您所需要的内容。
一个代码与框示例:https://codesandbox.io/s/fast-field-vyqlr1?file=/src/QuestionsAnswers.js:0-690

相关问题