输入文本框失去了关注键入反应js

时间:2017-06-02 09:18:33

标签: reactjs

输入文本框在输入时失去焦点。这是一段代码。无法理解问题所在。以下不是整个代码,但有点像这样。你能告诉我我在哪里弄错了吗

var PaymentDetailCard = React.createClass({
    getInitialState: function() {
        return {
            card: {
                        number: "",
                    userName: "",
                    dateWon: "",
                    prepayDue:"",
                    prepayApplied: "",

                    },
            }
    },componentDidMount: function() {
        this.setState( { card: this.props.card } );
   },

   getPrepayAppliedInput:function(){
       var input;
           input = 
           <input
               type="text"
               id="prepayAppliedCard"
               value={this.state.card.prepayApplied}
               onChange={this.change} maxLength ="10" 
       />;
      return( 
           <div><span>$</span>{input}</div>
           )
     },
    change:function(event){ 
           this.setState({prepayApplied: event.target.value});
           PaymentActions.sendRowNum(this.props.rownum);
           {this.props.onPrepayAppliedChange(event)};  
     },
    getUniqueID: function() {
         return Math.random().toString(36).substring(7);
    },
render: function() { 
return (<div>{this.getPrepayAppliedInput()} </div>
)
    }
});

2 个答案:

答案 0 :(得分:0)

首先,您应该像Facebook建议的那样从React.createClass转换为class PaymentDetailCard extends Component语法

其次,您的问题是您没有将change函数绑定到您的班级,因此在更改时,this指向input,而不是班级本身。打开控制台时,由于在此输入而不是类上调用setState,您可能会看到某种错误。

此外,关于您的代码的其他评论 - 您不应使用componentDidMount初始化状态 - 将card: this.props.card移至getInitialState

答案 1 :(得分:0)

您需要绑定onChange事件。这样的事情应该有效:

class PaymentDetailCard extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            card: {
                number: "",
                userName: "",
                dateWon: "",
                prepayDue: "",
                prepayApplied: ""
            }
        }
    }

    componentDidMount() {
        this.setState({card: this.props.card});
    }


    getPrepayAppliedInput() {
        let input = <input
                        type="text"
                        id="prepayAppliedCard"
                        value={this.state.card.prepayApplied}
                        onChange={this.change.bind(this)} maxLength="10"/>;

        return <div><span>$</span>{input}</div>
    }

    change(event) {
        this.setState({prepayApplied: event.target.value});
        PaymentActions.sendRowNum(this.props.rownum);
        {this.props.onPrepayAppliedChange(event)}
    }


    getUniqueID() {
        return Math.random().toString(36).substring(7);
    }

    render() {
        return (
            <div>{this.getPrepayAppliedInput()} </div>
        )
    }
}

React.render(<PaymentDetailCard />, document.getElementById('container'));

Here is the fiddle.