reactjs - 引用文献不起作用

标签 reactjs focus ref

我正在尝试做类似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/

相关文章:

javascript - React.forwardRef 导致样式组件错误

javascript - 为什么使用 setState(...) 时 console.log 为空?

wpf - 当面板中的元素具有焦点时更改 WPF StackPanel 背景颜色

android - 使编辑文本出现在android中设备的顶部和软键盘之间

javascript - 使用 forwardRef react 总是更新子组件,即使使用备忘录

c# - 为不需要的引用变量传递什么?

javascript - React : statusCode: 400,名称: "Error",消息: "The limit parameter "未定义“无效

node.js - React JS 同构渲染

reactjs - 如何在 TypeScript 中输入这个 'as' JSX 属性?

javascript - Sencha Touch 2 和.focus() : set cursor into textarea