简体   繁体   中英

React input field doesn't see value changing

When i picking date , event doesn't see anything, nothing happened, i cannot extract my value from input field. What **** ? Is it problem React or Datepicker? In datepicker manual nothing say about that, http://t1m0n.name/air-datepicker/docs/index.html

 class MyComponent extends React.Component { constructor(props) { super(props); this.state = { dueDate: 'Date and time' } } componentDidMount(){ this.initDatepicker(); } initDatepicker(){ $(this.refs.datepicker).datepicker(); } render(){ return ( <div> <h3>Choose date!</h3> <input value={this.state.dueDate} type='text' onChange={event => console.log(event)} ref='datepicker' /> </div> ) } } ReactDOM.render( <MyComponent />, document.getElementById('app') ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/js/datepicker.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/css/datepicker.min.css" rel="stylesheet"/> <div id="app"></div> 

You bound the input field value to the state property dueDate . Now if you want to modify it, you have to refresh the state property on input field change, therefore:

onChange={event => this.setState({dueDate: event.target.value})}

You wrote a controlled component. You set a state value to input element. If the state changes, your input value change. So you change the code below like,

  // input element
    <input value={this.state.dueDate} onChange={this.handleDueDate}/>

    // handleDueDate method
    handleDueDate(event){
        this.setState({
            dueDate: event.target.value
        })
    } 

If you change your code looks like, its works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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