2016-10-26 83 views
0

React非常新,我有一個輸入,我希望設置狀態quantity當點擊一個按鈕的數量更新,但我也希望能夠手動更新輸入也將更新狀態值,但不確定如何爲了達成這個?如何設置輸入默認值與狀態,還手動更新輸入?

JS

const Input = React.createClass({ 
    getInitialState() { 
     return { 
      quantity: 0 
     } 
    }, 

    updateQuantity() { 
      this.setState({ 
      quantity: this.state.quantity + 1 
     }); 
    }, 

    render() { 
     return (
      <div> 
       <input type="text" value={this.state.quantity}/> 
       <button onClick={this.updateQuantity}>Update</button> 
      </div> 
     ) 
    } 
}); 

JS小提琴http://jsfiddle.net/mwvjLqkg/

回答

0

您可以onChange事件添加到您的輸入,以改變quantity手動

const Input = React.createClass({ 
 
    getInitialState() { 
 
    return { 
 
     quantity: 0 
 
    } 
 
    }, 
 

 
    updateQuantity() { 
 
    this.setState({ 
 
     quantity: this.state.quantity + 1 
 
    }); 
 
    }, 
 

 
    handleChange(e) { 
 
    this.setState({ quantity: +e.target.value }) 
 
    }, 
 

 
    render() { 
 
    return <div> 
 
     <input 
 
     type="text" 
 
     value={this.state.quantity} 
 
     onChange={ this.handleChange } 
 
     /> 
 
     
 
     <button onClick={this.updateQuantity}>Update</button> 
 
    </div> 
 
    } 
 
}); 
 

 
ReactDOM.render(<Input />, document.body.querySelector('.js-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> 
 
<div class="js-app"></div>