reactjs - 参考不工作
问题描述
我正在尝试做类似的事情。但是,我希望输入字段保持焦点,直到用户单击菜单或任何子菜单之外的任何位置。我正在尝试按照 React 文档使用 refs(实际上是在尝试复制它),但我无法让它工作。
错误
“未捕获的 TypeError:_this.textInput.current.focus 不是函数”
代码(输入字段组件)
import React from 'react';
import styled from 'styled-components';
export default class TextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
focusTextInput = () => {
this.textInput.current.focus();
}
render = () => {
return (
<div>
<TextInputField
font={this.props.font}
fontSize={this.props.fontSize}
placeholder={"What?"}
type="text"
value={this.props.title}
titleLength={this.props.titleLength}
onChange={this.props.change}
onFocus={this.props.focus}
onBlur={this.props.blur}
id="titleInput"
textColor={this.props.textColor}
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
const TextInputField = styled.input`
width: 90%;
height: ${props => props.fontSize * 1.25}vw;
line-height: ${props => props.fontSize * 1.25}vw;
text-align: center;
position: absolute;
bottom: -12.5vw;
left: 5%;
margin: 0 auto;
background-color: transparent;
border: transparent;
text-overflow: ellipsis;
color: ${props => props.textColor};
font-size: ${props => props.fontSize}vw;
font-family: ${props => props.font};
&:hover {
background-color: rgba(0, 0, 0, 0.2);
}
&:focus {
outline: none;
background-color: rgba(0, 0, 0, 0.5);
}
`;
解决方案
you need to attach a innerRef on your styled component, something like this.
const StyledInput = styled.input`
some: styles;
`;
<StyledInput innerRef={comp => this.input = comp} />
// this.input.focus() works
推荐阅读
- windows - corecrt_memcpy_s.h:错误 C2065:'errno':未声明的标识符
- powershell - 计算长度超过 256 个字符的文件的哈希值?
- excel - 选择范围内的单元格
- ios - SwiftUI Core Data 无法从列表中删除多行
- java - 如何将 JSON 对象反序列化为具有循环引用的不可变类?
- python - 使用 Python 从 Google Firestore 读取数据,每日读取次数增加过快
- javascript - 如果 index 与 div 列表的索引相同,则附加对象值数组
- sql - MS访问连接两个表,获取唯一行
- ansible - Jinja2 如果定义了变量,则从引用变量的 Ansible 默认设置变量
- python-2.7 - 使用 pip 在 Windows 10 - 64 位上安装 Python 2.7- 32 位的人脸识别模块时遇到问题