ReactJS Click事件不在<div>上工作,但适用于<input />和<a>

时间:2017-12-03 23:56:24

标签: javascript jquery reactjs

I am learning ReactJS and I met this problem: ReactJS Click event not working on <div/> but works on <input/> and <a/>, here is my code:

class Item extends React.Component {
    handleClick = (e) => {
        e.preventDefault();
        alert(this.props.avatarUrl);

    }
    render() {
        return (
            <li>
                <a onClick={this.handleClick}>
                    <div style={{ backgroundImage: "url(" + this.props.avatarUrl + ")", width: '92px', height: '105px', cursor: 'pointer' }} >
                    </div>
                </a>
            </li>
        );
    }
}

class ItemCategory extends React.Component {
    render() {
        var items = [];
        for (var i = 0; i < this.props.itemList.length; i++) {
            if (this.props.itemType == this.props.itemList[i].Type) {
                items.push(<Item avatarUrl={this.props.itemList[i].Avatar} key={i} />);
            }
        }
        return (
            <ul className="dropdown-menu" role="menu">
                {items}
            </ul>
        );
    }
}

class ItemNav extends React.Component {
    constructor(props) {
        //do sth
    }
    componentWillMount() {
        //do sth
    }
    render() {
        return (
            <div>
            //sth other
                <ItemCategory ItemList={sth} itemType="4" team={sth} />
            //sth other
            </div>
        );
    }
}

ReactDOM.render(<ItemNav />, $("#nav-content-wrapper")[0]);

Now my problem is, the click event in the code above works, however, if I remove the a tag in item component, like this:

class Item extends React.Component {
    handleClick = () => {
        alert(this.props.avatarUrl);
    }
    render() {
        return (
            <li>
                <div onClick={this.handleClick} style={{ backgroundImage: "url(" + this.props.avatarUrl + ")", width: '92px', height: '105px', cursor: 'pointer' }} >
                </div>
            </li>
        );
    }
}

the click event is not triggered at all, I tried use bind.(this) or write the handleClick as return function but not working.

Anyone knows what is the problem? really appreciate any answer.

0 个答案:

没有答案