2017-04-21 12 views
1

입력을 사용하는 데 문제가 있습니다 ... 두 개의 입력이 있습니다. 하나는 자동 초점이고 다른 하나는 입력하지 않습니다. 그러나 두 번째 입력을 입력하면 포커스가 사라지고 포커스는 첫 번째 입력으로 돌아갑니다.타이핑 할 때 입력이 흐려짐

나는 뭔가를 입력 할 때 React rerenders my component를 읽었다. 나는 열쇠 소품 등을 넣으려고했지만 아무 것도 효과가 없었습니다. 내 양식 (회원 가입라는 구성 요소)에서

, 나는 다음과 같은 한 :

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 

가 어떻게이 문제를 해결할 수 :

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 

내 컴포넌트 입력이 코드가?

+0

바이올린이나 플 런커에 넣을 수 있습니까? – floor

+0

데모를 만들면 해결책이 있다고 생각하지만 테스트 할 수는 없습니다. – floor

+0

http://codepen.io/anon/pen/EmKQqy – leonero

답변

1

그렇게 간단한 해결책은 SignUp 구성 요소에 nameAutoFocus라는 다른 속성을 추가하고 true로 초기화하는 것입니다. 이 속성을 사용하여 자동 초점 부울 값을 설정합니다. 그런 다음 componentDidMount 메서드를 추가하고 nameAutoFocus를 false로 설정합니다. nameAutoFocus의 초기 값은 그 다음 componentDidMount 그래서 다음에 상태가 true로 자동 초점 속성을 설정하지 않습니다 변경 false로 설정 실행 초점주는 입력에 전달되기 때문에

class Signup extends React.Component { 
     constructor (props) { 
     super(props) 
     this.state = { 
      name: '', 
      email: '', 
     } 

     this.nameAutoFocus = true; //new 
     } 

     onSignup (e, userData) { 
     e.preventDefault() 
     this.props.onSignup(userData) 
     } 

     //new 
     componentDidMount() { 
     this.nameAutoFocus = false; 
     } 

     render() { 
     return (
      <main> 
      <div> 
       <h1>SIGNUP</h1> 

       <Input 
       id="name" 
       label="Name" 
       onChange={e => this.setState({ name: e.target.value })} 
       autofocus={this.nameAutoFocus} 
       /> 
       <Input 
       id="email" 
       label="E-mail" 
       onChange={e => this.setState({ email: e.target.value })} 
       /> 
      </div> 
      </main> 
     ) 
     } 
    } 

이 작동합니다. 이것은 기본적으로 처음 렌더링 될 때 한 번만 초점을줍니다.

codepen : http://codepen.io/floor_/pen/PmNRKV?editors=0011 실행을 클릭하는 것을 잊지 마십시오.

0

문제는 입력을 렌더링 할 때마다 ref에 대해 새 선 화살표 함수가 만들어지고 호출됩니다. 그래서 매번 inp.focus()을 실행합니다. 이것을 피하는 한 가지 방법은 클래스 컴포넌트를 사용하고 클래스 함수로 ref 콜백 메소드를 정의하는 것입니다.

class Input extends React.Component { 

    refCallback(inp){ 
    if(this.props.autofocus) inp.focus(); 
    } 

    render(){ 
    let input = '' 

    if (this.props.type === 'date') { 
     input = (
     <MaskedInput 
      ref={this.refCallback} 
      onChange={this.props.onChange} 
      mask="11/11/1111" 
      placeholder={this.props.placeholder} 
     /> 
    ) 
    } else { 
     input = (
     <input 
      ref={this.refCallback} 
      onChange={this.props.onChange} 
      id={this.props.id} 
      placeholder={this.props.placeholder} 
      type={this.props.type} 
     /> 
    ) 
    } 

    return (
     <div> 
     <label htmlFor={this.props.id}>{this.props.label}</label> 
     <br /> 
     {input} 
     </div> 
    ) 
    } 
} 

export default Input 

업데이트 codepen : http://codepen.io/anon/pen/jmqxWy

(내 앞의 코드는 내가 그것을 테스트 할 수 있기 때문에 몇 가지 문제가 있었다하지만 지금은 코드를 업데이트하고 작동합니다.)

+0

마지막 코멘트에 대해 유감이지만 작동했습니다. 나는 데모를 만들겠습니다. @ floor – leonero

+0

테스트 할 수 없었기 때문에 이전 코드에 몇 가지 문제가있었습니다. 하지만 지금은 코드를 업데이트하고 작동합니다. 또한 나는 업데이트 된 codepen을 포함시켰다. –

+0

@TharakaWijebandara이 솔루션은 나를 위해 작동하지 않으며 codepen에서도 작동하지 않습니다. – floor

관련 문제