[英]How to get element properties in reactjs
我正在嘗試獲取父容器元素的高度,以用作 SVG 背景元素的高度。
有沒有辦法獲得和傳遞這個屬性?
我不斷收到“TypeError:無法讀取未定義的屬性‘refs’”
const Services = ({ classes }) => {
return (
<div className={classes.Container} ref="container">//Element I want the height of
<div className={classes.BGContainer}>
<BGSVG width={'210'} height={this.refs.container.height} color={'blue'} />//Where I want to pass height to
</div>
<div className={classes.Services}>
{services.map((e, i) => (
<ServiceItem
title={e.title}
icon={e.icon}
info={e.info}
inverted={i % 2 === 1 ? true : false}
/>
))}
</div>
</div>
);
在函數式組件中,您需要像這樣使用名為useRef
的 React Hook:
const TextInputWithFocusButton = (props) => {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
如果您注銷inputEl
,您將看到是否記錄了對輸入元素的引用。 DOM 元素引用允許您訪問所引用的特定 DOM 元素的大多數屬性。
你還沒有綁定“這個”。 試試 height={() => this.refs.container.height}
如果你的服務組件在里面讓我們說 ServicesWrapper 組件,你應該做的是把它放在上面
`servicesWrapperContainerRef = React.createRef()`;
然后,在wrapper組件的JSX上
`ref={this.servicesWrapperContainerRef}`
然后,將它作為道具傳遞給 Services 組件,就像這樣 const Services = ({ classes, servicesWrapperContainerRef }) 然后你可以用它來找出父母的高度
`height={this.props.servicesWrapperContainerRef.current.clientHeight}`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.