如何让选择器在 React 中处理琐事游戏?



我正在使用开放琐事数据库API在反应中制作一个琐事游戏,我正在尝试获取它,以便有一个选择器按钮,当它下拉时,它会显示一个类别列表,当您单击它时,它会给您一个来自该类别的问题。我觉得我很接近,但只是错过了一块,想知道是否有人可以发现它或只是为我指出正确的方向?提前感谢您的时间和帮助。

这是我的应用程序代码.js:

import React from 'react'
import './App.css'
// import axios from 'axios'
import Questions from './components/questions'
import Categories from './components/categories'
import categorySelector from './components/categorySelector'
class App extends React.Component {
constructor (props) {
super(props)
this.state = {
questions: [],
categories: []
// score: 0,
}
}
render () {
return (
<div className='App'>
<h2>Trivia Game</h2>
<categorySelector
categories={Categories}
onSelect={event => this.questions(event.target.value)}
/>
</div>
)
}
}
export default App

这是我的categorySelector.js代码:

import React from 'react'
class categorySelector extends React.Component {
render () {
const { categories, onSelect } = this.props
return (
<div class='categorySelector'>
<select
value={categories} onChange={onSelect}
>
<option value=''>-- No category selected --</option>
{categories.map(category => (
<option value={category} key={category.id}>{category.name}</option>
))}
</select>
</div>
)
}
}
export default categorySelector

看起来选择标签没有取值 prop: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select

我修改了您的返回声明,如下所示

  • 将"class"更改为"className",因为class是Reactjs中的保留关键字
  • 从选择标签中删除了值属性
  • 将选项标签中的值属性更新为类别名称而不是对象
return (
<div class='categorySelector'>
<select onChange={onSelect}>
<option value=''>-- No category selected --</option>
{categories.map(category => (
<option value={category.name} key={category.id}>{category.name}</option>
))}
</select>
</div>
)

我还建议将反应类名大写,例如 CategorySelector 而不是 categorySelector。

应用程序组件中有几个拼写错误

  • 您正在将类别组件作为道具传递,而不是传递状态的类别切片。

  • 在 onSelect 事件中,this.questions(...( 表示您正在调用一个方法。但是,看起来您没有编写问题方法。 相反,如果你想在问题列表中"保存"选定的类别,你可以像这样调用setState:

  • 括号内的代码添加所选值,而不删除以前的选择。

    <categorySelector
    categories={this.categories}
    onSelect={event => this.setState({questions: [...this.state.questions, event.target.value]})}
    />
    

最新更新