gpt4 book ai didi

reactjs - 样式化组件输入焦点

转载 作者:行者123 更新时间:2023-12-03 13:24:27 26 4
gpt4 key购买 nike

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

试了一下,有效

关于reactjs - 样式化组件输入焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51300290/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com