ReactJS:无法输入到输入字段

时间:2015-04-25 17:01:33

标签: javascript reactjs

我开始学习反应并下载并遵循互联网上的任何教程。我正在努力建立好友列表 我有树组件,

friends_container:

InnerBase

add_friend:

update fact_stage set date_sk = (
  select ID -- identifier column in time_stage table
    from time_stage dim join fact_stage fact
    on (dim.year_time = fact.year_time
    and dim.month_time = fact.month_time
    and dim.day_time = fact.day_time)
   -- or instead of ON part use "USING (year_time, month_time, day_time)"
); 

show_list:

import React from 'react';
import AddFriend from './add_friend.jsx'
import ShowList from './show_list.jsx'

class FriendsContainer extends React.Component {

    constructor() {
        this.state = {
            friends: ['Jake Lingwall', 'Murphy Randall', 'Merrick Christensen']
        }
    }

    addFriend(friend) {
        this.setState({
            friends: this.state.friends.concat([friend])
        });
    }

    render() {
        return (
            <div>
                <h3> Add your friend to friendslist </h3>
                <AddFriend addNew={this.addFriend}/>
                <ShowList names={this.state.friends}/>
            </div>
        )
    }
}

export default FriendsContainer;

和app.jsx

import React from 'react';

class AddFriend extends React.Component {

    constructor() {
        this.state = {newFriend: ''};
    }

    updateNewFriend(e) {
        this.setState({
            newFriend: e.target.value
        })
    }

    handleAddNew() {
        this.props.addNew(this.state.newFriend);
        this.setState({
            newFriend: ''
        });
    }

    render() {
        return (
            <div>
                <input type="text" value={this.state.newFriend} onChange={this.updateNewFriend}/>
                <button onClick={this.handleAddNew}>Add Friend</button>
            </div>
        )
    }
}

AddFriend.propTypes = { addNew: React.PropTypes.func.isRequired };

export default AddFriend;

正如您在代码中看到的那样,我使用es6和babel作为转换编译器 我的问题是,我无法在输入字段中输入任何字母以将新朋友添加到朋友列表中。我做错了什么?

1 个答案:

答案 0 :(得分:2)

updateNewFriend方法的上下文中,this引用窗口对象而不是当前组件实例。您需要在将方法作为onChange事件处理程序传递之前绑定该方法。请参阅Function::bind

您有两种选择:

class AddFriend extends React.Component {

    constructor() {
        // ...
        this.updateNewFriend = this.updateNewFriend.bind(this);
        this.handleAddNew = this.handleAddNew.bind(this);
    }

}

class AddFriend extends React.Component {

   render() {
        return (
            <div>
                <input type="text" value={this.state.newFriend} onChange={this.updateNewFriend.bind(this)}/>
                <button onClick={this.handleAddNew.bind(this)}>Add Friend</button>
            </div>
        )
    }

}

请记住,Function::bind会返回一个新函数,因此render中的绑定会在每次渲染组件时创建一个函数,但性能影响可以忽略不计。