超级简单的示例可帮助您正确地开始。在使用之前,这需要做一些工作。这是它的作用:
这里没有什么特别棘手的。为了示例,我们使用本地状态,但是可以将其移至另一个状态管理实现,例如Redux。
该演示包含两个组件:
<Input />
-呈现受控输入<App />
渲染一个容器 <Input />
所述<App />
组件处理onPaste
事件,并从粘贴的数据到每个经过适当的值<Input />
分量
每个<Input />
组件都包含一个受控<input/>
元素,该元素仅由组成value
。
// A functional component to keep it simple
class Input extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
}
handleKeyDown = (event) => {
// Handle the delete/backspace key
if (event.keyCode === 8 || event.keyCode === 46) {
this.setState({
value: ''
});
return;
}
// Handle the tab key
if (event.keyCode === 9) {
return;
}
// Handle numbers and characters
const key = String.fromCharCode(event.which);
if (Number.isInteger(Number(key))) {
this.setState({
value: key
}, () => {
// Move focus to next input
this.refs[(this.props.index + 1) % 6].focus()
});
}
}
componentWillReceiveProps = (nextProps) => {
if (nextProps.value !== this.state.value) {
this.setState({
value: nextProps.value
})
}
}
render() {
return (
<div className="inputContainer">
<input
className="input"
value={this.state.value}
onKeyDown={this.handleKeyDown}
ref={(ref) => this.refs[this.props.index] = ref}
maxLength="1"
/>
</div>
)
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
code: null
}
}
handlePaste = (event) => {
event.clipboardData.items[0].getAsString(text => {
const code = text.split("").map((char, index) => {
if (Number.isInteger(Number(char))) {
return Number(char);
}
return "";
});
this.setState({
code
});
})
}
render() {
const code = this.state.code;
return (
<div className="container" onPaste={this.handlePaste}>
<Input value={code && code[0]} index={0} />
<Input value={code && code[1]} index={1} />
<Input value={code && code[2]} index={2} />
<div className="spacer">-</div>
<Input value={code && code[3]} index={3} />
<Input value={code && code[4]} index={4} />
<Input value={code && code[5]} index={5} />
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("app"));
.container {
display: flex;
}
.inputContainer {
flex: 1;
border: 1px solid #cccccc;
}
.inputContainer:last-child {
border-top-right-radius: 5px;
border-bottom-right-radius: 5px;
}
.inputContainer:first-child {
border-top-left-radius: 5px;
border-bottom-left-radius: 5px;
}
.spacer {
flex: 0.3 0;
text-align: center;
height: 40px;
line-height: 40px;
font-size: 24px;
}
.input {
width: 100%;
height: 40px;
line-height: 40px;
font-size: 24px;
text-align: center;
border: none;
outline: none;
border-radius: 5px;
box-sizing: border-box;
}
<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>
Test Code: 135791
<div id="app"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句