[英]React: onClick not rendering on div
更新:事实证明一切正常。 我的className三元组中只有一个错误,导致该类不适用。 但是,有人可以解释为什么onClick不会出现在检查器的<div>
上吗?
我有一个react组件,我想在其中使用onClick
事件呈现<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')),
)
});
此类问题可能是由于key
道具未呈现在列表项上(例如,警告显示)引起的。 key
原因在这里很重要,因为React使用唯一的逐项关键道具正确地解析/确定如何在渲染周期内更新列表中渲染的项目(即通过map()
)。
合并key
道具的一种简单方法是利用从地图回调传入的唯一“索引”,如下所示:
render() {
return (
<div>
{this.state.recipes[0]["recipes"].map((recipe, index) => {
return <Recipe
setRecipeAsSelected={this.setRecipeAsSelected}
selectedRecipe={this.state.selectedRecipe}
recipe={recipe} id={index} key={index }/>
})}
<Generate/>
</div>
)
}
另外,您在呈现的HTML中看不到onClick
属性的原因(例如,在dev-tools中可以看到),是因为dev-tools显示的呈现的HTML不是您在组件的render()
定义的实际JSX。 render()
方法。
您定义的JSX实际上是在幕后翻译成javascript的,因此, onClick
处理程序将附加到该<div />
的相应javascript Node对象上(这是通过addEventListener()
在内部完成的)。 因此,这使得将onClick
处理程序呈现到HTML标记中变得多余。
希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.