2016-06-27 46 views
1

我有一个输入值,我无法点击重置连接通过更新道具

class DiscountEditor extends Component { 
    render() { 
     <div className="inline field"> 
      <a className="ui reset" onClick={this.props.onReset}>Reset</a> 

      <input 
       value={this.props.discount} 
       onChange={this.props.onDiscountChanged}> 
      </input> 
     </div> 
    } 
} 

class SalesLine extends Component { 
    onReset(lineItem) { 
     this._discount = 0; 
     this.forceUpdate(); 
    } 

    render() { 
     <DiscountEditor 
      value={this._discount} 
      onChange={this.props.onDiscountChanged} 
      onReset={this.onReset.bind(this)} 
     </DiscountEditor> 
    } 
} 

后更新换代的输入值当我点击复位按钮DiscountEditor组件将被再次渲染和this.props.discount有正确的值为零,但输入值将保持不变,并且不会更新为零。 为什么?

回答

3

您称为支柱value但您使用的是this.props.discount。如果将其更改为

<input 
    value={this.props.value} 
    onChange={this.props.onDiscountChanged}> 
</input> 

它应该工作。

您还应该在您的SalesLine组件中将discount置于状态,而不是手动调用forceUpdate

class SalesLine extends Component { 
    constructor(props) { 
     super(props); 
     this.state = {discount: 0}; 
    } 

    onReset(lineItem) { 
     this.setState({discount: 0}); 
    } 

    render() { 
    return <DiscountEditor 
     value={this.state.discount} 
     onChange={this.props.onDiscountChanged} 
     onReset={this.onReset.bind(this)} 
    </DiscountEditor>; 
    } 
} 
1

分配_discount在构造函数中,并从那里上更新状态的状态

class SalesLine extends Component { 
    constructor(props) { 
     super(props); 
     this.state = {discount: this.props.discount}; 
    } 

    onReset(lineItem) { 
     this.setState({discount: 0}); 
    } 

    render() { 
    return <DiscountEditor 
     value={this.state.discount} 
     onChange={this.props.onDiscountChanged} 
     onReset={this.onReset.bind(this)} 
    </DiscountEditor>; 
    } 
}