使用派生值的受控输入可能会比较棘手-如果您需要能够显示无效或其他怪异的输入,那么…
始终将输入保持
value
在其组件本身中state
<input value={this.state.value} onChange={this.handleUpdate} // rest as above...得出初步
value
的getInitialState()
getInitialState: function() { return {value: this.props.user.balance / 100} }- 实现
componentWillReceiveProps(nextProps)
检测道具的值何时从上方改变并重新推导状态值
componentWillReceiveProps: function(nextProps) { if (this.props.user.balance != nextProps.user.balance) { this.setState({value: nextProps.user.balance / 100}) } }现在,当用户输入“ 33.”时,您可以使用来存储其文字输入
setState(),然后回调到父级。
handleUpdate: function(e) { var value = e.target.value this.setState({value: value}) this.props.onUserUpdate(parseFloat(value) * 100) }如果父母通过道具传回给孩子的值没有改变(
3300 ==3300在这种情况下),则
componentWillReceiveProps()不会做任何事情。
工作片段:
<script src="http://fb.me/react-with-addons-0.12.2.js"></script> <script src="http://fb.me/JSXTransformer-0.12.2.js"></script> <div id="example"></div> <script type="text/jsx;harmony=true">void function() { 'use strict'; var Parent = React.createClass({ getInitialState() { return {cents: 3300} }, _changevalue() { this.setState({cents: Math.round(Math.random() * 2000 + Math.random() * 2000)}) }, _onCentsChange(cents) { this.setState({cents}) }, render() { return <div> <p><strong>Cents:</strong> {this.state.cents.toFixed(0)} <input type="button" onClick={this._changevalue} value="Change"/></p> <Child cents={this.state.cents} onCentsChange={this._onCentsChange}/> </div> } }) var Child = React.createClass({ getInitialState() { return {dollars: this.props.cents / 100} }, componentWillReceiveProps(nextProps) { if (this.props.cents != nextProps.cents) { this.setState({dollars: nextProps.cents / 100}) } }, _onChange(e) { var dollars = e.target.value this.setState({dollars}) if (!isNaN(parseFloat(dollars)) && isFinite(dollars)) { this.props.onCentsChange(parseFloat(dollars) * 100) } }, render() { return <div> <input type="number" step="0.01" min="0" value={this.state.dollars} onChange={this._onChange}/> </div> } }) React.render(<Parent/>, document.querySelector('#example')) }()</script>


