React 风格的组件 - 如何访问原始 html

React Styled Components - How to access raw html

我有一个组件的引用,我正在我的应用程序中转换为 styled component。 ref 用于访问组件原始 html 元素上的 offsetHeight 和 scrollHeight 属性。将此组件切换为样式化组件后,ref 现在指向样式化组件而不是原始 html 元素,我不确定如何引用基本元素。这能做到吗?

示例:

const TextArea = styled.textarea`
  display: block;
  margin: 0 0 0 18%;
  padding: 4px 6px;
  width: 64%;
  font-size: 1rem;
  color: #111;`;

export default class Input extends Component {
  componentDidMount() {
    const height = this.textInput.scrollHeight;
    // do something....
  }
  render() {
    return (
      <div>
        <TextArea
          ref={(input) => this.textInput = input}
        ></TextArea>
      </div>
    );
  }
}

是的,可以做到。您可以使用 ReactDOM.findDOMNode() 访问原始 html。但是,请记住,不鼓励使用此方法。您可以在参考页面中阅读更多相关信息。

ref 传递给样式化组件将为您提供对 styled-components 包装器而不是 DOM 节点的引用。要获得对实际 DOM 节点 的引用,请传递 innerRef prop。 (参见 the docs

这是你需要做的:

const TextArea = styled.textarea``;

export default class Input extends Component {
  componentDidMount() {
    const height = this.textInput.scrollHeight;
    // do something....
  }
  render() {
    return (
      <div>
        <TextArea
          innerRef={(input) => this.textInput = input}
        ></TextArea>
      </div>
    );
  }
}