简体   繁体   English

为什么我不能在React中通过ref获取元素

[英]Why I can't get element by ref in React

I'm trying to get the element height via ref using React JS, but without success. 我正在尝试使用React JS通过ref获取元素高度,但没有成功。

I have something like this : 我有这样的事情:

render() {
    let cars = carData.filterCars(this.props.carsToShow, this.props.filters);
    return (
        <div>
            <div className="carList">
                <div className="cars" ref="cars">
                    {cars.map((car, i) => {
                        let carRef = "car-" + car.id;
                        return (
                           <div ref={carRef} key={i}>
                               <div>
                                   <div><img src={car.image_url} /></div>
                                   <div className="carNameAndDesc">
                                        <div>{car.make} {car.model}</div>
                                        <div>{car.price}</div>
                                   </div>
                               </div>
                             </div>
                         );
                      })}
                 </div>
            </div>

            <div ref="bigScreenDetails" className="bigScreenDetails">
               <div className="carDetailsBigScreen">
                    <CarDetails carID={this.state.carID}/>
               </div>
            </div>
        </div>
    );
}

And in componentDidMount I try to do it as follows : 在componentDidMount中,我尝试按如下方式执行:

componentDidMount(){
    let carRef = "car-" + this.props.carID;  //22
    let refs = this.refs[carRef].offsetHeight; //undefined
    let refs1 = this.refs["cars"].offsetHeight; //900
    let refs2 = this.refs["bigScreenDetails"].offsetHeight; //1400
}

I can't get ref of the div inside map. 我无法在地图里面得到div的参考。 Only for that ref I get undefined, for other refs I get the right values. 只有那个参考我得到未定义,对于其他参考我得到正确的值。

Any ideas? 有任何想法吗?

console.log(carRef) inside render returns console.log(carRef)内部渲染返回

"car-20"
"car-21"
"car-22"
.......
"car-35"

And console.log(carRef) inside componentDidMount returns 并且componentDlogMount中的console.log(carRef)返回

"car-22"

But if I console.log(this.refs) in componentDidMount I get : 但是如果我在componentDidMount中的console.log(this.refs)我得到:

在此输入图像描述

Thus only two refs insted of three. 因此,只有两个参考注册三个。

UPDATE UPDATE

As if there is absolutely no ref inside 好像里面绝对没有ref

{cars.map((car, i) => {
                    let carRef = "car-" + car.id;
                    return (
                       <div ref={carRef} key={i}>

                         </div>
                     );
                  })}

Here is the console log : 这是控制台日志:

let carRef = "car-" + carID;
    let refs = this.refs;
    let one = ReactDOM.findDOMNode(this.refs[carRef]);
    let two = this.carRefs;

    console.log("All refs : " + refs);
    console.log("Vikramaditya : " + one);
    console.log("Tom : " + two);

In first console.log I should see all three refs, but I see only two of them. 在第一个console.log中,我应该看到所有三个引用,但我只看到其中两个。

在此输入图像描述

Ideally, avoid using refs in the first place... 理想情况下,首先避免使用refs ...

If you need to use them for some reason, I'd recommend using the callback style. 如果由于某种原因需要使用它们,我建议使用回调样式。 This will allow you to use references to the elements themselves, rather than messing around with strings. 这将允许您使用对元素本身的引用,而不是使用字符串。

Looking at the docs , I'm not even sure whether string refs are supported any more... 看看文档 ,我甚至不确定是否支持字符串引用...

If I were you (and I was definitely sure I needed all these refs) I'd do something like this: 如果我是你(我肯定我需要所有这些参考)我会做这样的事情:

cars.map(car => (
    <div ref={ref => this.carRefs[car.id] = ref} key={car.id}>
    </div>
))

In your constructor, you can assign this.carRefs = {}; 在构造函数中,您可以指定this.carRefs = {}; .

Now you can access your cars in the this.carRefs object from inside componentDidMount . 现在,您可以从componentDidMount中的this.carRefs对象访问您的汽车。

 class TestComponent extends React.Component { constructor() { super(); this.carRefs = {}; } componentDidMount() { console.log(this.carRefs); } render() { return (<div> {this.props.cars.map(({id}) => <div key={id} ref={ref => this.carRefs[id] = ref}></div>)} </div>); } } const cars = [{id: 1}, {id: 2}]; ReactDOM.render(<TestComponent cars={cars} /> , document.getElementById("root")); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM