更新:事实证明一切正常。我只是在我的 className Ternary 中有一个错误导致该类不适用。但是,有人可以解释为什么 onClick 没有出现在 <div>
上吗?在检查器中?
我有一个 react 组件,我想在其中呈现 <div>
用onClick
事件。然而,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
引起的prop 未在列表项上呈现(即如警告所示)。原因key
这里重要的是 React 使用唯一的每项 key 属性来正确地解析/确定如何在渲染周期中更新列表中渲染的项目(即通过 map()
)。
合并 key
的简单方法prop是利用map回调传入的唯一“index”,如下:
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>
)
}
更新
此外,您没有看到 onClick
的原因呈现的 HTML 中的属性(即在开发工具中可以看到)是因为开发工具显示的呈现的 HTML 不是您在组件的 render()
中定义的实际 JSX。方法。
您定义的 JSX 实际上在幕后转换为 javascript,因此,onClick
处理程序附加到该 <div />
的相应 javascript Node 对象(这是通过 addEventListener()
在内部完成的)。因此,这使得渲染 onClick
处理程序到 HTML 标记中是多余的。
希望对您有所帮助!
关于javascript - react : onClick not rendering on div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53075706/