【发布时间】: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>
)
}
}
【问题讨论】:
-
我不这么认为,但感谢您的检查。样式化的组件让事情变得有点棘手。
-
您是否尝试过使用粗箭头直接内联
ref={(input) => { this.inputRef = input; }}创建引用并使用简单的this.inputRef.focus();聚焦元素?