2017-10-02 7 views
1

의 입력 [유형 = "번호"]에 대한 포커스가 설정된 포커스 React set focusReact focus with timeout을 읽은 후에 입력시 focus을 설정하기위한 올바른 크로스 브라우저 옵션이 무엇인지 아직도 혼란 스럽습니다.조건부 렌더링

table에 렌더링 후 포커스가있는 조건부 렌더링 입력에 문제가 있습니다. 여기에서 inputtd입니다.

componentDidUpdate 1) 해결 방법 :

//... 
componentDidUpdate() { 
    this.input && this.input.focus(); 
} 

render() { 
    const show = this.state.isShown; 

    return (
    <td className="editable"> 
     {!show ? (
     <input 
      type="number" 
      ref={(input) => { this.input = input }} 
      value={this.state.value} 
      onBlur={this.save} 
      onKeyPress={e => 
      e.which === 13 || e.keyCode === 13 ? this.save() : null} 
     /> 
    ) : (
     <span onClick={this.onTdClick}>{this.props.name}</span> 
    )} 
    </td> 
); 
} 

이 솔루션은 크롬, IE11, 에지에서 작동하지만 작동하지 않습니다 최신 파이어 폭스 (span 클릭 후 입력 이벤트가 표시되지 않습니다

합니다.

//... 
componentDidUpdate() { 
    if (!this.state.isShown) { 
    requestAnimationFrame(() => { 
     this.input && this.input.focus(); 
    }) 
    } 
} 

render() { 
    // same above 
} 
: requestAnimationFrame

2) 솔루션3210

이 솔루션은 Chrome, IE11, Edge에서 작동하지만 focus을 설정하려고 시도하면 Firefox에 입력이 표시되지 않습니다.

3) 에서는 setTimeout (콜백, N과 솔루션) :

//... 
    componentDidUpdate() { 
    if (!this.state.isShown) { 
     setTimeout(() => { 
     this.input && this.input.focus() 
     }, 50); 
    } 
    } 

    render() { 
    // same above 
    } 

이 사건은 크롬, IE11, 에지 및 (마지막으로) 파이어 폭스에 대한 작동하지만, 이것은 대부분의 "추악한"한 것 같다.

P. autoFocus ATTR, 나는 조건부 렌더링, 그래서 그래서 click.

후 설정 초점을 필요로 여기,이 경우에없는 내 질문입니다 : 우리는/파이어 폭스에 대한 setTimeout을 설정 승을이 문제를 해결하는 올바른 방법을 가지고있다?

라이브 테스트 예 : codepen

답변

1
import React from 'react'; 

const MyInput = React.createClass({ 

    componentDidMount(){ 
     this.elem.focus(); 
    }, 

    render(){ 
     return(
      <input 
       ref={(elem) => {this.elem = elem}} 
       type="text" 
      /> 
     ); 
    } 
}); 
export default MyInput; 

원하는 <MyInput/>을 렌더링합니다. 렌더링 후 초점이 맞춰질 것입니다. Safari, Chrome, Firefox에서 테스트되었습니다.

+0

고맙습니다. 귀하의 솔루션을 테스트했고 실제로 ** Firefox/etc **에서'input [ "text"]'에 대해서는 작동하지만'input [ "number"]'에 대해서는 작동하지 않습니다. (파이어 폭스는 심지어 입력을 보여줍니다) [codepen] (https://codepen.io/anon/pen/eGExyJ?editors=0010) – dieTrying