react-bootstrap上的onClick事件

时间:2017-04-16 16:36:45

标签: javascript reactjs events react-bootstrap

我正在努力学习意思,而我正试图制作一个简单的口袋妖怪查找器。

问题在于,我对连接到组件的事件感到麻烦。

以下是主要观点:

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;

不幸的是,不会触发附加到按钮或形式控件的事件......

有人知道这可能是错的吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

就像Ved提到的那样,您应该使用onChange={this.handleClick.bind(this)}代替onChange = {this.handleClick}

但是,您可以为类Pokedex添加构造函数以提高可读性。

export class Search extends Component {
  constructor(props, context) {
    super(props, context);

    this.handleClick = this.handleClick.bind(this);
  }

  // the rest of code...
}