【问题标题】:styled component input focus样式化的组件输入焦点
【发布时间】:2025-12-18 06:50:01
【问题描述】:

我试图在组件安装时专注于输入。输入组件是一个样式化的组件,因此我使用 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>
    )
  }
}

【问题讨论】:

  • 可能是*.com/questions/28889826/…的欺骗
  • 我不这么认为,但感谢您的检查。样式化的组件让事情变得有点棘手。
  • 您是否尝试过使用粗箭头直接内联ref={(input) =&gt; { this.inputRef = input; }} 创建引用并使用简单的this.inputRef.focus(); 聚焦元素?

标签: reactjs styled-components


【解决方案1】:

请试试这个

import React from 'react';
import styled from 'styled-components';

const UrlInput = styled.input`
  background-color: white;
`;

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

  componentDidMount() {
    if (this.inputRef.current) {
      this.inputRef.current.focus(); // This should work
    }
  }

  render() {
    return(
        <UrlInput innerRef={this.inputRef} />
    )
  }
}

如果您切换到 React v16 和样式化组件 v4,您可以使用 ref 而不是 innerRef

<UrlInput ref={this.inputRef} />

也请检查一下

对任何样式组件的 ref 的原生支持,由于 React v16,不再需要 innerRef

https://medium.com/styled-components/announcing-styled-components-v4-better-faster-stronger-3fe1aba1a112

【讨论】:

    【解决方案2】:

    setTimeout 成功了。

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

    【讨论】:

      【解决方案3】:

      对于样式化的组件,请使用属性 innerRef 而不是 ref。从他们的文档here 得到它。

      文档中的示例:

      <StyledInput innerRef={this.input} />
      

      试一试,成功了

      【讨论】: