React样式化组件-如何访问原始HTML [英] React Styled Components - How to access raw html
问题描述
我对要转换为样式化组件中的组件的引用我的应用程序.ref用于访问组件原始html元素上的offsetHeight和scrollHeight属性.一旦我将这个组件切换到一个样式化的组件,引用现在就指向该样式化的组件,而不是原始的html元素,而且我不确定如何引用基本元素.能做到吗?
I have a ref on a component I am converting over to a styled component in my app. The ref is used to access the offsetHeight and scrollHeight properties on the raw html element of the component. Once I switched this component to a styled component, the ref now points to the styled component instead of the raw html element, and I'm unsure how to reference the base element. Can this be done?
示例:
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>
);
}
}
推荐答案
将 ref
传递给样式化组件将为您提供对 styled-components
包装器的引用,而不是DOM节点.要获得对实际DOM节点的引用,请传递innerRef属性.(请参见文档)
Passing ref
to a styled component will give you a ref to the styled-components
wrapper, not the DOM node. To get a ref to actual DOM node pass the innerRef prop. (see 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>
);
}
}
这篇关于React样式化组件-如何访问原始HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!