猿问

react 中的 componentDidMount 无法获取真实dom

在 render 中设置 ref 后,componentDidMount 中无法获取真实节点,具体代码如下,请指教?


export default class Content extends Component{

  componentDidMount() {

    console.log(this.p);

  }


  render() {

    const arr = [{content:'内容一'},{content:'内容二'},{content:'内容三'}];

    

    const domP = arr.map((item,i) => {

      return <p ref={(dom) => this.p = dom} key={i}>{item.content}</p>

    });

    retuen (

      <div>

        {domP}

      </div>

    );

  }

}


慕姐4208626
浏览 738回答 1
1回答

HUWWW

先说原因:map方法遍历数组导致this.p被不断的重新赋值,所以最后在componentDidMount中拿到的永远都是数组最后一次遍历创建的dom节点。提供解法:export default class Content extends Component{&nbsp; componentDidMount() {&nbsp; &nbsp; console.log(this.p0);&nbsp; &nbsp; console.log(this.p1);&nbsp; &nbsp; console.log(this.p2);&nbsp; }&nbsp; render() {&nbsp; &nbsp; const arr = [{content:'内容一'},{content:'内容二'},{content:'内容三'}];&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; const domP = arr.map((item,i) => {&nbsp; &nbsp; &nbsp; return <p ref={(dom) => this['p' + i] = dom} key={i}>{item.content}</p>&nbsp; &nbsp; });&nbsp; &nbsp; retuen (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; {domP}&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答