所以我目前无法专注于输入字段-我有一张卡片,上面有一个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;
最佳答案
首先创建一个参考:
myInput = React.createRef();
分配参考:
ref={this.myInput}
然后,要聚焦
myInput
,请使用:this.myInput.current.focus()
关于javascript - 无法获得输入字段以使点击集中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52259859/