2017-11-09 7 views
0

ReactJS 및 Material UI를 사용하여 응용 프로그램을 만들고 있습니다. FormControl 구성 요소 안에 Input 구성 요소가 있습니다. 사용자가 FormControl을 클릭했을 때 (그러나 여전히 Input 컴포넌트 외부에있을 때) Input 컴포넌트에 초점을 맞추고 싶습니다. 어떻게이 일을 성취 할 수 있습니까? 나는 심판과 시도했지만 나는 그것을 할 수 없습니다 :해당 영역 외부를 클릭하면 MUI 입력 구성 요소에 포커스가 설정됩니다.

<FormControl 
    onClick={this.textInput.focus()} 
    style={{ display: 'block', cursor: 'text' }} 
> 
<Input 
    error={this.props.error} 
    disabled={this.props.disabled} 
    ref={(input) => { this.textInput = input; }} 
/> 
</FormControl> 

감사를 사전에 도움

+0

을 :

이 코드는 작동합니다 (https://material-ui-next.com/customization/api/#internal-components 참조) 정의되지 않은 재산 '초점'을 읽을 수 없습니다 – Anto

답변

2

,하지만 난 여기에 두 가지 문제가 있다고 생각 :

대신 사용해보십시오. 첫째, onClick에 대한 값은 함수가 아니므로 아직 정의되지 않은 참조에서 구성 요소가 인스턴스화되면 focus을 호출합니다. 당신은 호출을 래핑하여이 문제를 해결할 수 있습니다 () => this.textInput.focus()를 (또는하는 방법/인스턴스 속성을 만들 수 있습니다.)

둘째, material-uiwithStyles 고차 구성 요소에 Input 구성 요소를 래핑, 당신은 ref를 사용하는 경우, 그것은을 의미 래핑 된 구성 요소에는 focus 메서드가 없습니다. 대신, 실제 input DOM 요소에 대한 참조를 만드는 inputRef 소품을 사용할 수 있습니다. 내가 할

.. 
    <FormControl 
    onClick={() => this.textInput.focus()} 
    style={{ display: 'block', cursor: 'text' }} 
    > 
    <Input 
     error={this.props.error} 
     disabled={this.props.disabled} 
     inputRef={(input) => { this.textInput = input; }} 
    /> 
    </FormControl> 
.. 
0

문제는 컨텍스트와 클릭 이벤트가 FormControl 요소에서 처리되는 방식으로 수 있습니다하십시오. 내가 material-ui 잘 알고 아니에요

constructor(props) { 
    super(props); 
    this.setFocus = this.setFocus.bind(this); 
} 
setFocus() { 
    this.textInput.focus(); 
} 
render() { 
    return(
    <FormControl 
     onClick={this.setFocus} 
     style={{ display: 'block', cursor: 'text' }} 
    > 
     <Input 
     error={this.props.error} 
     disabled={this.props.disabled} 
     ref={(input) => { this.textInput = input; }} 
     /> 
    </FormControl> 
); 
}