无法获得输入字段以使点击集中

时间:2018-09-10 14:19:12

标签: javascript reactjs

所以我目前无法专注于输入字段-我有一张卡片,上面有一个onClick处理程序。一旦单击它-它会显示输入字段,但是,我无法使输入字段聚焦:

出问题的关键区域位于我设置了引用的renderTextField内,然后在this.myInput.focus()中调用handleClickInside,但还是没有运气。

下面的代码

import React, { Component } from 'react';
import { CSSTransition, transit } from 'react-css-transition';
import Text from './Text';
import Card from './Card';
import MenuIcon from '../icons/MenuIcon';

const style = {
  container: { height: '60px', width: '300px' },
  input: { border: 'none', fontSize: '14px', background: '#ff000000' },
  icon: { position: 'absolute', right: '10px', top: '18px' },
};

class Input extends Component {
  state = {
    clickedOutside: true,
    value: '',
  };

  componentDidMount() {
    document.addEventListener('mousedown', this.handleClickOutside);
  }

  componentWillUnmount() {
    document.removeEventListener('mousedown', this.handleClickOutside);
  }

  myRef = React.createRef();

  myInput = React.createRef();

  handleClickOutside = (e) => {
    if (!this.myRef.current.contains(e.target)) {
      this.setState({ clickedOutside: true });
    }
  };

  handleClickInside = () => {
    this.setState({ clickedOutside: false });
    this.myInput.current.focus();
  }

  renderField = () => {
    const { clickedOutside, value } = this.state;
    return (
      <div>
        <CSSTransition
          defaultStyle={{ transform: 'translate(0, -2px)' }}
          enterStyle={{ transform: transit('translate(0, -16px)', 150, 'ease-in-out') }}
          leaveStyle={{ transform: transit('translate(0, -2px)', 150, 'ease-in-out') }}
          activeStyle={{ transform: 'translate(0, -16px)' }}
          active={!clickedOutside || value.length > 0}
        >
          <Text>Password</Text>
          { this.renderTextField() }
        </CSSTransition>
      </div>
    );
  }

  renderTextField = () => {
    const { clickedOutside, value } = this.state;
    return (
      <input
        ref={this.myInput}
        style={style.input}
        type="text"
        value={value}
        placeholder={!clickedOutside ? 'Enter Password...' : null}
        disabled={clickedOutside}
        onChange={e => this.setState({ value: e.target.value })}
      />
    );
  }

  renderIcon = () => (
    <div style={style.icon}>
      <MenuIcon />
    </div>
  )

  render() {
    return (
      <div ref={this.myRef} onClick={this.handleClickInside} >
        <Card override={style.container}>
          { this.renderField() }
          { this.renderIcon() }
        </Card>
      </div>
    );
  }
}

export default Input;

1 个答案:

答案 0 :(得分:1)

首先创建一个参考:

myInput = React.createRef();

分配裁判:

ref={this.myInput}

然后,要聚焦myInput,请使用:

this.myInput.current.focus()