【发布时间】:2017-09-17 19:52:04
【问题描述】:
我在使用输入时遇到问题...我有两个输入:一个有自动对焦,另一个没有。但是,当我输入第二个输入时,它会失去焦点,焦点会返回到第一个输入。
我读过 React 在我输入内容时会重新渲染我的组件。我尝试放置一个关键道具等,但没有任何效果。
在我的表单(一个名为 Signup 的组件)中,我有以下内容:
import React from 'react'
import Input from '../../components/Input'
import styles from './styles.scss'
class Signup extends React.Component {
constructor (props) {
super(props)
this.state = {
name: '',
email: '',
}
}
onSignup (e, userData) {
e.preventDefault()
this.props.onSignup(userData)
}
render () {
return (
<main className={styles.wrapper}>
<div className={styles.formSide}>
<h1>SIGNUP</h1>
<Input
id="name"
label="Name"
onChange={e => this.setState({ name: e.target.value })}
autofocus={true}
/>
<Input
id="email"
label="E-mail"
onChange={e => this.setState({ email: e.target.value })}
/>
</div>
</main>
)
}
}
Signup.propTypes = {
onSignup: React.PropTypes.func.isRequired
}
export default Signup
我的组件输入有这个代码:
import React, { PropTypes } from 'react'
import MaskedInput from 'react-maskedinput'
import styles from './styles.scss'
function Input (props) {
let iconComp
if (props.icon) {
iconComp = (<img src={props.icon} alt="Icon" />)
}
let input = ''
if (props.type === 'date') {
input = (
<MaskedInput
ref={inp => inp && props.autofocus && inp.focus()}
onChange={props.onChange}
mask="11/11/1111"
placeholder={props.placeholder}
className={styles.input}
/>
)
} else {
input = (
<input
ref={inp => inp && props.autofocus && inp.focus()}
onChange={props.onChange}
id={props.id}
placeholder={props.placeholder}
type={props.type}
className={styles.input}
/>
)
}
return (
<div className={styles.wrapper}>
<label htmlFor={props.id} className={styles.label}>{props.label}</label>
<br />
{input}
{props.error &&
<span className={styles.error}>
{props.errorMessage}
</span>
}
{iconComp}
</div>
)
}
Input.propTypes = {
id: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
icon: PropTypes.string,
placeholder: PropTypes.string,
type: PropTypes.string,
autofocus: PropTypes.bool,
onChange: PropTypes.func.isRequired,
error: PropTypes.bool,
errorMessage: PropTypes.string
}
Input.defaultProps = {
icon: '',
placeholder: '',
type: 'text',
autofocus: false,
error: false,
errorMessage: ''
}
export default Input
我该如何解决这个问题?
【问题讨论】:
-
你能把它放在fiddle或plunker吗?
-
如果你做一个演示,我想我有一个解决方案,但我无法测试它。
-
谢谢,我有一个简单的解决方案。
标签: javascript reactjs