2017-02-25 10 views
1

React 상태에서는 새로운 값을 설정하기가 쉬웠습니다.이 값은 일부 입력을 렌더링하기위한 조건이었으며 그 다음 상태 콜백으로 해당 입력에 집중했습니다. 입력했던 아직 다시 쓰게 성분 반응 때문에Mobx and React. 관찰 가능한 변경 후 초점 입력을 처리하는 방법?

handleToggleInput() { 
    const showInput = !this.state.showInput 
    this.setState({ showInput },() => showInput && this.refs.input.focus()) 
} 

render() { 
    if(this.state.showInput) { 
    <input ref="input" type="text /> 
    } 
} 

지금을 Mobx로 전환하면,

@observable showInput = false; 

handleToggleInput() { 
    this.showInput = !this.showInput 
    this.showInput && this.refs.input.focus() 
} 

render() { 
    if(this.showInput) { 
    <input ref="input" type="text /> 
    } 
} 

이 실패 할 수없는 경우. 다시 렌더링 할 때 대기 및 검색 방법이 있습니까?

+0

매우 흥미 렌더링 후 즉시 코드를 실행합니다. 그것은 당신이 [** 초점 연기 **] (http://jsbin.com/kuzariquce/edit?js, 출력)하면 작동합니다. 조건부로 입력을 숨기지 않으면 지연없이 작동합니다. 바라건대 MobX 전문가가 이에 대한 의견을 밝힐 수 있기를 바랍니다. – Tholle

+1

@Tholle 매우 영리합니다! 이것은 현재 잘 작동 할 것이지만, React Fiber 또는 다른 React 구현은 향후 재 스케줄링으로 인해 문제가 될 수 있습니다. – Schovi

답변

1

setState의 콜백은 상태가 설정되고 구성 요소가 다시 렌더링 된 후에 실행됩니다. MobX는 이에 해당하지 않습니다. React가 UI를 렌더링 한 후에이 메소드를 사용하여 포커스를 맞 춥니 다.

componentDidUpdate: function(prevProps, prevState){ 
    this.refs.input.focus(); 
}, 

먼저

componentDidMount: function(){ 
    this.refs.input.focus(); 
}, 

React set focus on input after render

https://facebook.github.io/react/docs/react-component.html#componentdidupdate

+0

또한 StackOverflow 질문에 표시된 것처럼 ref 콜백을 사용하기 시작합니다. 'ref = "input"을 사용하는 것은 더 이상 사용되지 않습니다. – aitchnyu

+0

그러나 나는 "보이지 않는다"에서 "보여 주다"로의 관측 가능한 변화를 알지 못합니다. ComponentDidUpdate는 다른 이유로 인해 발생할 수 있습니다. 솔루션이지만 추한 것은 핸들러에서 'this._focusOnUpdate = showInput' 속성을 유지 한 다음 라이프 사이클 이벤트를 반영하는 것입니다. 그러나 내가 말했듯이 ( – Schovi

+0

새로 입력 된 것을 원한다면 그 입력에'autofocus' 속성을 사용하지 않을까요? – aitchnyu