繁体   English   中英

将onChange事件传递给子组件

[英]React passing onChange event down to child component

我有以下内容:

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

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

console.log(this.getSearchedValue());

既然你没有传递任何东西,那么e是未定义的。

暂无
暂无

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

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