简体   繁体   English

反应:onClick不在div上渲染

[英]React: onClick not rendering on div

UPDATE: Turns out everything was working fine. 更新:事实证明一切正常。 I just had an error in my className Ternary that was causing the class not to apply. 我的className三元组中只有一个错误,导致该类不适用。 However, could someone explain why onClick does not appear on the <div> in the inspector? 但是,有人可以解释为什么onClick不会出现在检查器的<div>上吗?

I have a react component in which I would like to render a <div> with an onClick event. 我有一个react组件,我想在其中使用onClick事件呈现<div> However, the onClick is not rendering for some reason. 但是,由于某些原因, onClick无法呈现。 I have no errors in the console other than the warning: Each child in an array or iterator should have a unique "key" prop. 除了警告,控制台中没有其他错误: Each child in an array or iterator should have a unique "key" prop.

The <div> that actually renders looks like this: <div id="1" class="unselected">Peppered Chicken</div> 实际呈现的<div>看起来像这样: <div id="1" class="unselected">Peppered Chicken</div>

My code looks like this. 我的代码如下所示。 Thoughts? 思考?

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')),
    )
});

This kind of issue can be caused by the key prop not being rendered on list items (ie as the warning reads). 此类问题可能是由于key道具未呈现在列表项上(例如,警告显示)引起的。 The reason key is important here is that React uses the unique per-item key prop to correctly resolve/determine how to update items rendered in a list (ie via map() ) during the render cycle. key原因在这里很重要,因为React使用唯一的逐项关键道具正确地解析/确定如何在渲染周期内更新列表中渲染的项目(即通过map() )。

One easy way to incorporate the key prop is to make use of the unique "index" passed in from the map callback, as follows: 合并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>
    )
}

Update 更新

Also, the reason you don't seeing the onClick attribute in the rendered HTML (ie as can be seen in dev-tools), is because the rendered HTML that dev-tools shows is not the actual JSX that you defined in your component's render() method(s). 另外,您在呈现的HTML中看不到onClick属性的原因(例如,在dev-tools中可以看到),是因为dev-tools显示的呈现的HTML不是您在组件的render()定义的实际JSX。 render()方法。

The JSX that you define is actually translated to javascript behind the scenes, and as a result, the onClick handler gets attached to the corresponding javascript Node object for that <div /> (this is internally done via addEventListener() ). 您定义的JSX实际上是在幕后翻译成javascript的,因此, onClick处理程序将附加到该<div />的相应javascript Node对象上(这是通过addEventListener()在内部完成的)。 This therefore makes rendering the onClick handler into the HTML markup redundant. 因此,这使得将onClick处理程序呈现到HTML标记中变得多余。

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM