简体   繁体   中英

why my onclick function didn't work in react

Hi i didn't understand why my onclick function didn't work. my function create run herself 2 time at the loading of the page but not when i click on the button

  import React, { Component, PropTypes } from 'react'; import { createContainer } from 'meteor/react-meteor-data'; import { Topics } from '../api/topic.js'; import Topic from './Topic.jsx'; class AppCreate extends Component { render(){ return( <div className="container"> <form> <input type="text" placeholder="donnez un nom a votre Topic" className="topic"></input> <input type="button" value="Créer" onClick={this.create()}></input> </form> </div> ); } create(e){ {var test = document.getElementsByClassName("topic").value; console.log(test);} } } AppCreate.propTypes = { topics: PropTypes.array.isRequired }; export default createContainer(() => { return { topics: Topics.find({}).fetch(), }; }, AppCreate); 

Why it doesn't work

When you're passing onClick={this.create()} you're actually passing the return value of the function, and not the function it self. As a side effect, this will also cause that function to be called when a render occurs, not only when a user actually clicks.

Solution

You want to pass the function itself to be called, notice there are no parentheses () :

onClick={this.create}

If you need to access the component instance in the click handle

You'll also want to bind this (the instance of your component) inside your method, eg to access this.state you'll have to bind that value

onClick={this.create.bind(this)}

With this the execution inside create() will have a this value equal to the instance of your component, allowing you to access its attributes and methods like this.props , this.state and other methods you have defined on the component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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