开发者社区> 问答> 正文

#React 在回调引用和findDOMNode()中,哪个是首选选项?

#React 在回调引用和findDOMNode()中,哪个是首选选项?

展开
收起
因为相信,所以看见。 2020-05-07 16:36:20 833 0
1 条回答
写回答
取消 提交回答
  • 阿里,我所有的向往

    最好使用回调引用而不是findDOMNode()API。因为findDOMNode()将来无法在React中进行某些改进。

    使用以下传统方法findDOMNode:

    class MyComponent extends Component {
      componentDidMount() {
        findDOMNode(this).scrollIntoView()
      }
    
      render() {
        return <div />
      }
    }
    
    

    推荐的方法是:

    class MyComponent extends Component {
      constructor(props){
        super(props);
        this.node = createRef();
      }
      componentDidMount() {
        this.node.current.scrollIntoView();
      }
    
      render() {
        return <div ref={this.node} />
    
    

    } }

    2020-05-07 16:37:42
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
利用编译将 Vue 组件转成 React 组件 立即下载
React Native 全量化实践 立即下载
React在大型后台管理项目中的工程实践 立即下载