2017-06-02 102 views
0

输入文本框在输入时失去焦点。这是一段代码。不能明白问题在哪里。以下内容不是完整的代码,但它有点像这样。能否请你告诉我在哪里,我在做错误输入文本框丢失焦点输入反应js

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

回答

0

首先,你应该为Facebook建议

其次摆脱React.createClassclass PaymentDetailCard extends Component语法,你的问题是,你是没有约束力的change功能到你的班级,因此在变更时,this指向input,而不是班级本身。当您打开控制台时,您可能会看到某种错误,因为在此输入上调用setState而不是类。

此外,关于你的代码另一条评论 - 你不应该使用componentDidMount初始化状态 - 移动card: this.props.cardgetInitialState

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.