简体   繁体   English

为什么我的onclick功能没有起作用

[英]why my onclick function didn't work in react

Hi i didn't understand why my onclick function didn't work. 嗨,我不明白为什么我的onclick功能不起作用。 my function create run herself 2 time at the loading of the page but not when i click on the button 我的函数在页面加载时创建自己运行2次,但是当我点击按钮时却没有

  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. 当你传递onClick={this.create()}你实际上是传递了函数的返回值,而不是它自己的函数。 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 您还需要在方法中绑定this (组件的实例),例如,要访问this.state您必须绑定该值

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. 这样,create()中的执行将具有与组件实例相等的this值,允许您访问其属性和方法,如this.propsthis.state和您在组件上定义的其他方法。

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

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