Styled Component 输入框聚焦

9

当组件挂载时,我想将焦点放在输入框上。该输入框组件是一个样式化组件,因此我使用 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>
    )
  }
}

可能是 https://dev59.com/414b5IYBdhLWcg3wnS0e 的重复问题。 - borisrorsvort
我不这么认为,但感谢您的检查。Styled component 使事情变得有点棘手。 - quantdaddy
2
你尝试过直接使用箭头函数创建ref并将其嵌入到代码中吗?例如:ref={(input) => { this.inputRef = input; }},然后通过简单的this.inputRef.focus();来聚焦元素吗? - borisrorsvort
3个回答

4

对于styled components,使用innerRef属性而不是ref属性。这是从他们的文档中获取的。

来自文档的示例:

<StyledInput innerRef={this.input} />

我试过了,它有效。


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和styled components v4,可以使用ref代替innerRef

<UrlInput ref={this.inputRef} />

同时,请检查这个

在 React v16 中,任何样式化组件都原生支持 ref 属性,不再需要使用 innerRef。

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


0

setTimeout 做到了这一点。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接