样式化的组件输入焦点

qua*_*ddy 7 reactjs styled-components

组件安装时,我尝试着眼于输入。输入组件是样式组件,因此我使用innerRef来获取对该元素的引用。但是,安装组件时,输入不会获得焦点。我检查了该节点是否实际上正在获取对DOM节点的引用。我的逻辑找不到任何问题。谢谢您的帮助。

import React, { Component } from 'react';
import { findDOMNode } from 'react-dom';
import styled, { keyframes } from 'styled-components';

const UrlInput = styled.input`
  width: 400px;
  height: 34px;
  background-color: white;
  display: inline-block;
  outline: none;
  padding-left: 10px;
  font: 400 14px 'Source Sans Pro', 'sans-serif';
  ::placeholder {
    color: rgb(100,100,100);
    font: 400 14px 'Source Sans Pro', 'sans-serif';
  }
`

class AddUrl extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      url: ''
    }
    this.inputRef = React.createRef();
  }

  componentDidMount() {
    const node = findDOMNode(this.inputRef.current);
    node && node.focus();
  }


  render() {
    return(
      <AddUrlWrapper>
        <UrlInput placeholder={"Paste URL here"}
          innerRef={this.inputRef}
          type="text"
          value={this.state.url}
          onChange={(event) => this.setState({url: event.target.value})}/>
        <FetchButton>Fetch</FetchButton>
      </AddUrlWrapper>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

Fle*_*lam 4

对于样式组件,请使用 propinnerRef而不是ref. 从他们的文档中得到它。

文档中的示例:

<StyledInput innerRef={this.input} />
Run Code Online (Sandbox Code Playgroud)

尝试了一下,有效