React Redux - 获取用户输入值

时间:2018-02-19 17:07:46

标签: reactjs input redux

我想获取用户的输入值,然后在我的Redux操作fetchData中使用它。我想在input.onChange时更改组件状态中的变量,然后从中获取字符串以使用参数调用我的方法。

我在this is undefined上发现错误handleChange

import React, { Component } from 'react';
import { connect } from "react-redux";
import { fetchData } from "../actions/fetchData";

class SearchBar extends Component {

    constructor() {
        super()

        this.state = {
            tags: ''
        }
    }

    buttonClicked() {
        this.props.fetchData(this.state.tag)
    }

    handleChange(e) {
        this.setState({ tags: e.target.value })
    }

    render() {
        return (
            <section className="section">
                <div className="columns">
                    <div className="column is-half is-offset-one-quarter">
                        <div className="field has-addons">
                            <div className="control is-expanded">
                                <input className="input" type="text" placeholder="dog" onChange={this.handleChange}/>
                            </div>
                            <div className="control">
                                <a className="button is-info" onClick={this.buttonClicked}>
                                    Random!
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        )
    }
}

export default connect(null, { fetchData })(SearchBar);

我在这里想念什么?

1 个答案:

答案 0 :(得分:2)

你必须将this绑定到你的函数,试试这个:

...
constructor() {
  super()

  this.state = {
      tags: ''
  }
  this.buttonClicked = this.buttonClicked.bind(this);
  this.handleChange = this.handleChange.bind(this);
}
...

另外,请查看why do you need to bind this on the constructor