Мне нужно знать высоту Реагировать Компонент внутри другого компонента React. Я знаю, что высота элемента может быть достигнута вызовом this.cmref.current.clientHeight
. Я ищу что-то вроде этого:
дочерний компонент:
const Comp = () =>{
return(
<div>some other stuff here</div>
)
}
export default Comp
родительский компонент:
class App extends React.Component{
constructor(props){
super(props);
this.compref = React.createRef();
}
componentDidSomething(){
const height = this.compref.current.clientHeight;
//which will be undefined
}
render(){
return(
<div>
<Comp ref = {this.compref} />
</div>
)
}
}
Это возможно? Заранее спасибо.
@ApplePearPerson Это не работает. Вы уверены? потому что я только что протестировал обычный элемент div и получил правильный результат, но то же самое не будет работать с компонентом реакции.
Извините, я попал в ту же ловушку, что и вы. Я добавлю ответ с рабочим фрагментом.
Вам нужно будет на самом деле ссылаться на div дочернего компонента, чтобы получить нужный элемент вместо самого дочернего компонента. Для этого вы можете передать функцию дочернему элементу, который затем передается в div. Рабочий пример ниже:
const Comp = (props) =>{
return(
<div ref = {props.onRef}>some other stuff here</div>
)
}
class App extends React.Component{
constructor(props){
super(props);
this.compref = React.createRef();
}
componentDidMount(){
const height = this.compref.current.clientHeight;
//which will be undefined --- No more!
console.info('height: ', height);
}
onCompRef = (ref) => {
this.compref.current = ref;
}
render(){
return(
<div>
<Comp onRef = {this.onCompRef} />
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src = "https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id='root' style='width: 100%; height: 100%'>
</div>
const Comp = React.forwardRef((props, ref) => (
<div ref = {ref}> some other stuff here </div>
));
class App extends React.Component{
constructor(props){
super(props);
this.compref = React.createRef();
}
componentDidMount(){
const height = this.compref.clientHeight;
console.info("hieght", height);
}
render(){
return(
<div>
<Comp ref = {(el) => this.compref = el} />
</div>
)
}
}
ReactDOM.render(<App />, document.querySelector("#app"))
Не могли бы вы попробовать этот способ. Надеюсь, поможет. Пожалуйста, обратитесь к передовым ссылкам https://reactjs.org/docs/forwarding-refs.html
Да, это возможно и должно работать с приведенным выше кодом.