【问题标题】:How to focus a styled component?如何聚焦样式化的组件?
【发布时间】:2018-02-22 09:44:55
【问题描述】:

我有一个样式组件:

const StyledComponent = styled.div`
    ...
`;

我想在安装使用它的组件时focus它:

class someComponent extends React.Component {
    componentDidMount() {
        this.sc.focus();
    }

    render() {
        return (
            <StyledComponent innerRef={(elem) => { this.sc = elem; }}>
                ...
            </StyledComponent>
        );
    }
}

这种技术不起作用 - 有解决办法吗?

【问题讨论】:

  • 您是否尝试过在 StyledComponent 中使用 tabindex={0} 属性?
  • @vinhas 这对我不起作用,将组件上的 tabIndex="0" 设置为 jsx 属性确实有效

标签: styled-components


【解决方案1】:

尝试将autoFocus 属性传递给您的StyledComponent,例如&lt;StyledComponent autoFocus /&gt;

【讨论】:

    【解决方案2】:

    这个link 有一个包含 React 16 React.createRef() 和回调方法的示例。

    您是否尝试过设置autoFocus 属性,还是不适合您的用例?

    【讨论】:

    • styled-components 对我来说失去了自动对焦 ?
    【解决方案3】:

    如果不使用tabIndex ("tabindex" in normal HTML),您将无法聚焦非交互式元素。 “div”元素被认为是非交互式的(与锚链接“a”和按钮控件“button”不同。)

    如果你希望能够聚焦这个元素,你需要添加一个 tabIndex 属性。如果需要自动添加它,您可以使用.attrs,这样您就不需要每次都编写道具。

    【讨论】:

    • .attrs 也拒绝添加它:-(
    猜你喜欢
    • 2020-05-23
    • 2021-04-19
    • 2018-12-20
    • 2023-03-26
    • 2019-11-15
    • 2020-04-25
    • 2022-01-07
    • 2019-11-27
    • 2020-10-27
    相关资源
    最近更新 更多