反应时的 onClick 事件-bootstrap

onClick event on react-bootstrap

我正在尝试学习 MEAN,我正在尝试制作一个 Easy Pokemon finder。

问题是我在处理附加到组件的事件时遇到了问题。

这里是主视图:

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

这是搜索组件:

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;

不幸的是,它不会被触发既不是按钮也不是表单控件的事件...

任何人都知道它可能是错的吗?

谢谢!

就像Ved提到的,你应该使用onChange={this.handleClick.bind(this)}而不是onChange={this.handleClick}

但是,您可以为 class 添加构造函数 Pokedex 以获得更多可读性。

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