简体   繁体   English

react-bootstrap 上的 onClick 事件

[英]onClick event on react-bootstrap

I'm trying to learn MEAN and I was trying to make an Easy Pokemon finder.我正在尝试学习 MEAN 并且我正在尝试制作一个简单的口袋妖怪查找器。

The thing is that i'm having troubles with events attaching to a component.问题是我在将事件附加到组件时遇到了麻烦。

Here is the main view:这是主要观点:

 import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; /* Import Components */ import Search from './components/Search/Search'; import { Grid, Row, Col } from 'react-bootstrap'; /* Import Actions */ import { fetchByName } from './PokedexActions'; // Import Style //import styles from './Pokedex.css'; class Pokedex extends Component { handleFind= (name) =>{ this.props.dispatch(fetchByName({name})); }; render() { return ( <Grid> <Row> <Col md={4}> <Search findPokemon={this.handleFind}/> </Col> <Col md={4}></Col> <Col md={4}></Col> </Row> </Grid> ); } } const mapStateToProps = (state) => { return {}; }; const mapDispatchToProps = (dispatch) => { return {}; }; Pokedex.contextTypes = { router: React.PropTypes.object }; export default connect( mapStateToProps, mapDispatchToProps )(Pokedex);

and here it's the search componenet:这是搜索组件:

 import React, { Component, PropTypes } from 'react'; import { ControlLabel, FormControl, Button } from 'react-bootstrap'; export class Search extends Component { handleClick(){ console.log("algo"); this.props.findPokemon('eevee'); //console.log(this.refs.name); } render() { return ( <div> <ControlLabel>Pokemon Search</ControlLabel> <FormControl type="text" placeholder="Pokemon" ref="name" onChange={this.handleClick}/> <Button bsStyle="primary" onClick={this.handleClick}>Find</Button> </div> ); } } Search.propTypes = { findPokemon: PropTypes.func.isRequired }; export default Search;

Unfortunately it won't get fired the events attached to neither button nor form Control...不幸的是,它不会触发附加到按钮和表单控件的事件...

Anybody knows what it could be wrong?有谁知道这可能是什么问题?

Thanks!谢谢!

Just like Ved mentioned, you should use onChange={this.handleClick.bind(this)} instead of onChange={this.handleClick} .就像Ved提到的,你应该使用onChange={this.handleClick.bind(this)}而不是onChange={this.handleClick}

However, you could add constructor for class Pokedex to get more readability.但是,您可以为类Pokedex添加构造函数以获得更多可读性。

export class Search extends Component {
  constructor(props, context) {
    super(props, context);
    
    this.handleClick = this.handleClick.bind(this);
  }
  
  // the rest of code...
}

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

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