source

반응 JS의 입력 요소 자동 포커스

lovecheck 2023. 3. 13. 20:34
반응형

반응 JS의 입력 요소 자동 포커스

이 컴포넌트에 렌더링된 입력 태그의 포커스를 자동 설정할 수 없습니다.내가 뭘 놓쳤지?

class TaskBox extends Component {
  constructor() {
    super();
    this.focus = this.focus.bind(this);
  }

  focus() {
    this.textInput.focus();
  }

  componentWillUpdate(){
    this.focus();
  }

  render() {
    let props = this.props;
    return (
      <div style={{display: props.visible ? 'block' : 'none'}}>
        <input
        ref={(input) => { this.textInput = input; }}
        onBlur={props.blurFN} />
        <div>
          <div>Imp.</div>
          <div>Urg.</div>
          <div>Role</div>
        </div>
        <div>
          <button>Add goal</button>
        </div>
      </div>
    )
  }
}

어떤 도움이라도 감사합니다.

자동 포커스에 사용할 수 있는 특성이 있습니다.autoFocus, 우리는 그것을 사용하는 대신 입력 요소의 자동 초점에 사용할 수 있습니다.ref.

사용.autoFocus입력 요소 포함:

<input autoFocus />

사용할 수도 있습니다.ref단, 레퍼런스에서는 포커스 메서드를 올바른 장소에서 호출해야 합니다.고객은 그것을 호출하고 있습니다.componentWillUpdate라이프 사이클 메서드.이 메서드는 초기 렌더링 중에 트리거되지 않습니다.그 대신 이 메서드를 사용합니다.componentDidMount라이프 사이클 방법:

componentDidMount(){
    this.focus();
}

show Component Update:는 항상 렌더 메서드 전에 호출되며 재렌더링이 필요한지 건너뛸 수 있는지 여부를 정의할 수 있습니다.이 메서드는 초기 렌더링에서는 호출되지 않습니다.컴포넌트 상태가 변경되었을 경우에만 호출됩니다.

componentWillUpdate는 다음 명령어가 실행되자마자 호출됩니다.shouldComponentUpdatetrue를 반환했습니다.

componentDidMount:렌더 메서드가 실행되자마자 componentDidMount 함수가 호출됩니다.이 방법으로 DOM에 액세스 할 수 있기 때문에, DOM 조작이나 데이터 취득 조작을 정의할 수 있습니다.모든 DOM 상호 작용은 항상 여기서 발생합니다.

참고 자료: https://facebook.github.io/react/docs/react-component.html

입력에 ID를 설정한 다음.setAttribute('autoFocus', true)초점을 맞추고 싶을 때 요소까지

언급URL : https://stackoverflow.com/questions/42324423/autofocus-an-input-element-in-react-js

반응형