从数组onClick渲染对象

时间:2018-07-17 16:07:37

标签: javascript arrays reactjs object

我想从每个数组中呈现一个onClick问题。如果我单击“真值数组”,则应该从该数组中提出一个问题;如果单击“胆敢”数组,请执行相同的操作。我的项目是使用reactjs创建真相或敢于尝试的游戏,

我的代码如下:

Questions.js

const truth = [
  {question: "Question 1", hasAppeard: false},
  {question: "Question 2", hasAppeard: false},
  {question: "Question 3", hasAppeard: false},
  {question: "Question 4", hasAppeard: false}
]

const dare = [
  {question: "Question 5", hasAppeard: false},
  {question: "Question 6", hasAppeard: false},
  {question: "Question 7", hasAppeard: false},
  {question: "Question 8", hasAppeard: false}
]

App.js

class App extends Component {
  constructor() {
  super();
  this.state = {
    truthQuest: null,
    dareQuest: null
  }
}

handleRandomTruth = () => {
  this.setState({
  truthQuest: Math.round(Math.random() * 9 + 1)
  })
}

handleRandomDare = () => {
  this.setState({
  dareQuest: Math.round(Math.random() * 9 + 1)
  })
}

render() {
  return (
    <div className="App">
      <div className="timer">
        <CountdownTimer />
      </div>

      <div className="current-player">
        <h3>current player</h3>
      </div>

      <div className="next-player">
        <h3>next player</h3>
      </div>

      <div className="questions">
         {truth[Object.keys(this.state.truthQuest
         {dare[this.state.dareQuest]}
      </div>

      <button className="btn-truth" onClick= 
       {this.handleRandomTruth}>Truth</button>
      <button className="btn-dare" onClick= 
       {this.handleRandomDare}>Dare</button>
      <button className="btn-home" >Home</button>
  </div>

谢谢!

1 个答案:

答案 0 :(得分:0)

为了一次只显示一个问题,在组件HTML中,您只需在状态上设置一个K'变量即可,而不是一个单独的真/敢问题,因为这是不必要的。我还做了其他一些小的更改,因为它们使事情变得更简单。

name := "PageRank"

version := "1.0"

scalaVersion := "2.11.8"

libraryDependencies ++= Seq(
     "org.apache.spark" % "spark-core_2.11" % "2.2.1" % "provided",
     "org.apache.spark" % "spark-sql_2.11" % "2.2.1" % "provided",
     "org.apache.spark" % "spark-graphx_2.11" % "2.2.1" % "provided"
 )