Last active
October 13, 2019 11:21
-
-
Save dedoyle/120d25aed006d09c0770f761ecaafc77 to your computer and use it in GitHub Desktop.
InputNumber 组件
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from 'react' | |
import InputNumber from './InputNumber.js' | |
function App() { | |
const [value, setValue] = useState('aaa') | |
return ( | |
<div> | |
<div>{value}</div> | |
<InputNumber | |
value={value} | |
onChange={e => { | |
setValue(e.target.value) | |
}} | |
></InputNumber> | |
<InputNumber | |
defaultValue={value} | |
onChange={e => { | |
setValue(e.target.value) | |
}} | |
></InputNumber> | |
</div> | |
) | |
} | |
export default App |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react' | |
import PropTypes from 'prop-types' | |
import './index.css' | |
class InputNumber extends Component { | |
constructor (props) { | |
super(props) | |
this.state = { | |
innerValue: '' | |
} | |
} | |
static propTypes = { | |
value: PropTypes.string, | |
defaultValue: PropTypes.string, | |
onChange: PropTypes.func | |
} | |
isControl () { | |
return 'value' in this.props | |
} | |
get value () { | |
if (this.isControl()) { | |
return this.props.value | |
} else { | |
return this.state.innerValue | |
} | |
} | |
render () { | |
return ( | |
<div> | |
<input | |
value={this.value} | |
onChange={e => { | |
if (!this.isControl()) { | |
this.setState({ | |
innerValue: e.target.value | |
}) | |
} | |
this.props.onChange(e) | |
}} | |
/> | |
</div> | |
) | |
} | |
componentDidMount () { | |
this.setState({ | |
innerValue: this.props.defaultValue | |
}) | |
} | |
} | |
export default InputNumber |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment