bgm*_*ter 6 javascript css reactjs styled-components
我有一个组件的参考我将转换为我的应用程序中的样式组件.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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
mxs*_*tbr 22
传递ref给样式化组件将为您提供styled-components包装器的引用,而不是DOM节点.要获得对实际DOM节点的引用,请传递innerRef prop.(见文档)
这是你需要做的:
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3631 次 |
| 最近记录: |