如何处理onClick而不是href <a>

时间:2018-06-08 16:07:16

标签: javascript reactjs

So I'm using a jquery plugin and for it to work properly I have to have my book now button (styled to look like a button) be inside an anchor tag. My react component looks like this:

export default class Header extends React.Component {
constructor(props){
    super(props);
    this.state ={
        showModal: false,
    };
    this.openModal = this.openModal.bind(this);
    this.exitModal = this.exitModal.bind(this);
}


openModal(){
    console.log('hello');
    this.setState(()=> ({showModal: true}));
    return false;
}

exitModal(){
    this.setState(()=> ({showModal: false}));
}

render(){
    return (
        ...

            <li>
                <a id="navbar-book" href="#" onClick={this.openModal} className="book-button"><span>Book Now</span></a>
            </li>
        ...
             <BookModal 
                showModal={this.state.showModal}
                exitModal={this.exitModal}
            />  

    )
}

};

I don't want to have an href but if I don't have it my dropotron plugin won't work on it. I've already tried to return false from the function in hopes that href wouldn't run. All I need it to do is run the modal.

2 个答案:

答案 0 :(得分:2)

您可以使用以下按钮:

<button onClick={this.openModal}>Book Now</button>

但如果您真的必须使用链接,则必须在点击事件上使用 preventDefault ,如下所示:

openModal(event){
    event.preventDefault();
    this.setState(()=> ({showModal: true}));
    return false;
}

答案 1 :(得分:1)

如何用按钮替换它?

<button onClick={this.openModal}>Book Now</button>