我正在尝试做类似this的事情。但是,我希望输入字段保持焦点,直到用户单击菜单或任何子菜单之外的任何地方。我正在尝试使用 React 文档中的 refs (实际上试图复制它),但我无法让它工作。
错误
"Uncaught TypeError: _this.textInput.current.focus is not a function"
代码(输入字段组件)
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);
}
`;
最佳答案
你需要在你的样式组件上附加一个innerRef,就像这样。
const StyledInput = styled.input`
some: styles;
`;
<StyledInput innerRef={comp => this.input = comp} />
// this.input.focus() works 🎉
关于reactjs - 引用文献不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50664834/