IT虾米网

reactjs之样式化组件输入焦点

youxin 2025年12月25日 程序员 46 0

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

请您参考如下方法:

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

文档中的示例:

<StyledInput innerRef={this.input} /> 

试了一下,有效


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!