将onChange事件传递给子组件

时间:2016-10-08 14:42:51

标签: javascript reactjs

我有以下内容:

import React from 'react';
import {render} from 'react-dom';

import Form from './form.jsx';

import axios from 'axios';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      location: ''
    };
  }
  getSearchedValue(e) {
    this.setState({ location: e.target.value });
  }
  searchNearPlaces (e) {
    e.preventDefault();

    console.log(this.getSearchedValue());

    const clientID = 'xxxxxxxxxxx',
          clientSecret = 'xxxxxxxxxxxxx',
          version = 'v=20140806';
    let location = this.state.location,
        url = 'https://api.foursquare.com/v2/venues/explore?client_id=' + clientID + '&client_secret=' + clientSecret + '&near=' + location + '&' + version;

    axios.get(url)
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
  }
  render () {
    return (
        <section className="main">
            <Form action={this.searchNearPlaces.bind(this)} value={this.getSearchedValue.bind(this)} />
        </section>
    );
  }
}

render(<App/>, document.getElementById('app'));

和表单组件:

import React from 'react';

class Form extends React.Component {
    render () {
        return (
            <form className="form-group">
                <input type="text" onChange={this.props.value} />
                <input onClick={this.props.action} type="submit" />
            </form>
        );
    }
}

export default Form;

我在键入'london'之后点击提交的那一刻例如我收到以下错误:

Uncaught TypeError: Cannot read property 'target' of undefined

指的是:

  getSearchedValue(e) {
    this.setState({ location: e.target.value });
  }

1 个答案:

答案 0 :(得分:3)

可能因为代码中的这一行:

console.log(this.getSearchedValue());

由于您没有传递任何内容,e未定义。

相关问题