2017-07-07 89 views
1

嗨,我不明白为什么我的onclick函数不起作用。我的函数来创建自己运行时间2在页面加载但不是当我点击按钮为什么我的onclick函数在反应中不起作用

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);

+4

[React onClick函数在渲染时触发]可能重复(https://stackoverflow.com/questions/33846682/react-onclick-function-fires-on-render) –

回答

3

为什么它不工作

当你通过onClick={this.create()}你实际上是传递函数的返回值,而不是它自己的函数。作为副作用,这也会导致在渲染发生时调用该函数,而不仅仅是当用户实际点击时。

解决方案

你想通过函数本身被调用,注意有没有括号()

onClick={this.create}

如果您需要访问点击的组件实例处理

您还需要绑定this(th例如你的组件的实例),例如访问this.state你必须bind那些重视

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

有了这个执行的内部创建()将有一个this值等于您的组件的情况下,允许您访问其属性和方法,如this.props,this.state和您在组件上定义的其他方法。

+0

看起来像他缺少绑定的创建函数... this.create = this.create.bind(this) – Yoeri

+0

它的工作非常感谢@bakkal – alpheonix

+0

如果我使用这个函数我必须使用bind(this)?什么是绑定(这)? – alpheonix

相关问题