React-Bootstrap上的OnClick事件



我试图学习卑鄙的含义,而我正试图使一个简单的口袋妖怪查找器。

问题是,我在附加到组件的事件时遇到麻烦。

这是主要视图:

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}

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

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

最新更新