【发布时间】:2018-10-31 03:07:38
【问题描述】:
更新:结果一切正常。我的 className 三元组中出现了一个错误,导致该类不适用。但是,有人可以解释为什么 onClick 没有出现在检查器中的<div> 上吗?
我有一个反应组件,我想在其中渲染一个带有onClickevent 的<div>。但是,由于某种原因,onClick 没有呈现。除了警告之外,我在控制台中没有任何错误:Each child in an array or iterator should have a unique "key" prop.
实际渲染的<div> 如下所示:<div id="1" class="unselected">Peppered Chicken</div>
我的代码如下所示。想法?
import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (<div><RecipesList/></div>)
}
}
class RecipesList extends React.Component {
constructor(props) {
super(props);
this.state = {
recipes: [{recipes:[]}],
selectedRecipe: null
};
this.setRecipeAsSelected = this.setRecipeAsSelected.bind(this)
}
componentDidMount() {
fetch('/recipes')
.then(response => response.json())
.then(recipes => this.setState({recipes}));
}
setRecipeAsSelected(recipeID) {
this.setState({selectedRecipe: recipeID})
}
render() {
return (
<div>
{this.state.recipes[0]["recipes"].map((recipe, index) => {
return <Recipe setRecipeAsSelected={this.setRecipeAsSelected} selectedRecipe={this.state.selectedRecipe} recipe={recipe} id={index}/>
})}
<Generate/>
</div>
)
}
}
class Recipe extends React.Component {
constructor(props){
super(props);
this.setThisAsSelected = this.setThisAsSelected.bind(this)
}
setThisAsSelected() {
this.props.setRecipeAsSelected(this.props.id)
}
render() {
return (
<div onClick={this.setThisAsSelected} key={this.props.id} id={this.props.id} className={this.props.selectedRecipe === this.props.key ? "bg-primary" : "test"}> {this.props.recipe} </div>
)
}
}
class Generate extends React.Component {
render() {
return (
<div>
<button>GENERATE</button>
</div>
)
}
}
document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(
<App/>,
document.body.appendChild(document.createElement('div')),
)
});
【问题讨论】:
-
Each child in an array or iterator should have a unique "key" prop要解决此问题,请在映射到<Recipe />组件时,在RecipleList的渲染方法中添加键。即<Recipe ... key={index} /> -
class="unselected"来自哪里?它不在代码中。 -
我猜应该是“测试”。为了清楚起见,我更改了它,但忘记在元素上更新它
-
上述更新中的解决方案
-
@JonnyB 刚刚更新了答案,以包括按要求添加的详细信息 :-)
标签: javascript reactjs onclick