React ref的用法总结

React的ref有3种用法:
1:字符串用法(这种用法已经被废弃了,在版本16以前还可以使用)
2:回调函数
在这里,我常用的就是回调函数,其触发的节点在componentDidMount后和componentWillMount后。
在类组件中使用(父组件)

import Home from './components/Home/index'

 componentDidMount() {
      console.log(this.homes._abc());
  }

render() {
  retrurn (
          <div>
              <Home ref={ (item) => { this.homes = item} }> </Home>
        </div>
  )
}

子组件:

export default class Home extends Component{
    _abc() {
        console.log("this is abc")
    }
    render() {
        return (
            <div className="home">这是首页</div>
        )
    }
}

3:React.createRef()

在ReactCreateRef.js文件中,可以看到如下代码:

// an immutable object with a single mutable value
export function createRef(): RefObject {
  const refObject = {
    current: null,
  };
  if (__DEV__) {
    Object.seal(refObject);
  }
  return refObject;
}

说明返回的有一个current属性。
使用方法:

class Child extends React.Component{
    constructor(props){
        super(props);
        this.myRef=React.createRef();
    }
    componentDidMount(){
        console.log(this.myRef.current);
    }
    render(){
        return <input ref={this.myRef}/>
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容