首页 > 解决方案 > 参考不工作

问题描述

我正在尝试做类似的事情。但是,我希望输入字段保持焦点,直到用户单击菜单或任何子菜单之外的任何位置。我正在尝试按照 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);
}
`;

标签: reactjsfocusref

解决方案


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 

推荐阅读