【问题标题】:How to use the styled-component property innerRef with a React stateless component?如何将 styled-component 属性 innerRef 与 React 无状态组件一起使用?
【发布时间】:2017-09-06 22:10:30
【问题描述】:

我有以下样式组件:

const Component = styled.div`
    ...
`;

const Button = (props) => {
    return (
        <Component>
            ...
        </Component>
    );
};

export default styled(Button)``;

我想获得对 Component 底层 div 的引用。当我执行以下操作时,我得到null:

import Button from './Button.js';

class Foo extends React.Component {

    getRef = () => {
        console.log(this.btn);
    }

    render() {
        return (
            <Button innerRef={elem => this.btn = elem} />
        );
    }
}

任何想法为什么我会收到null 以及有关如何访问底层 div 的任何建议?

注意:我这样做export default styled(Button)``; 的原因是为了可以轻松扩展导出样式的组件。

【问题讨论】:

标签: reactjs styled-components


【解决方案1】:

我设法通过将一个函数作为 prop 传递给我所针对的样式组件,然后将 ref 作为函数的参数传回来实现这一点:

const Component = styled.div`
    ...
`;

const Button = (props) => {
    return (
        <Component innerRef={elem => props.getRef(elem)}>
            ...
        </Component>
    );
};

export default styled(Button)``;

...

import Button from './Button.js';

class Foo extends React.Component {

    getRef = (ref) => {
        console.log(ref);
    }

    render() {
        return (
            <Button getRef={this.getRef} />
        );
    }
}

【讨论】:

    【解决方案2】:

    将 ref prop 传递给样式化组件将为您提供 StyledComponent 包装器的实例,但不会传递给底层 DOM 节点。这是由于 refs 的工作方式。所以不可能直接在样式化的组件包装器上调用 DOM 方法,比如 focus。

    因此,为了获得对实际包装的内部 DOM 节点的引用,回调被传递给 innerRef 属性,如下例所示,以将包装在 Styled 组件“Input”中的“input”元素聚焦在悬停上。

      const Input = styled.input`
      padding: 0.5em;
      margin: 0.5em;
      color: palevioletred;
      background: papayawhip;
      border: none;
      border-radius: 3px;
    `;
    
    class Form extends React.Component {
      render() {
        return (
          <Input
            placeholder="Hover here..."
            innerRef={x => { this.input = x }}
            onMouseEnter={() => this.input.focus()}
          />
        );
      }
    }
    
    render(
      <Form />
    );
    

    注意:- 不支持字符串引用(即 innerRef="node"),因为它们在 React 中已被弃用。

    【讨论】:

      猜你喜欢
      • 2020-08-15
      • 1970-01-01
      • 2019-09-16
      • 2019-03-26
      • 2019-05-11
      • 1970-01-01
      • 2021-03-07
      • 2020-06-09
      • 2021-12-19
      相关资源
      最近更新 更多