Refs не работает - PullRequest
       13

Refs не работает

0 голосов
/ 03 июня 2018

Я пытаюсь сделать что-то похожее на это .Однако я бы хотел, чтобы поле ввода оставалось в фокусе, пока пользователь не щелкнет где-нибудь, кроме как внутри меню или любого из подменю.Я пытаюсь использовать ссылки, следующие за документацией React (фактически пытаюсь продублировать ее), но не могу заставить ее работать.

Ошибка

"UncaughtОшибка типа: _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);
}
`;

1 Ответ

0 голосов
/ 03 июня 2018

вам нужно прикрепить innerRef к вашему стилизованному компоненту, что-то вроде этого.

const StyledInput = styled.input`
  some: styles;
`;

<StyledInput innerRef={comp => this.input = comp} />

// this.input.focus() works ?
...