当组件挂载时,我想将焦点放在输入框上。该输入框组件是一个样式化组件,因此我使用 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();
来聚焦元素吗? - borisrorsvort