<万博manbetx平台>react怎样取得ref的值 - 万博manbetx平台中文网

react怎样取得ref的值

react取得ref值的方法:

第一种形式

定义

constructor(props) {
  super(props);
  this.state = {};
  this.textInput = React.createRef(); //看这里
}
绑定
render() {
  return (
    <div>
      <p>测试原生事件与合成事件的区别</p>
      <div>
        <button ref={this.textInput} //看这里 className="button" onClick={this.onReactClick}>
          点击
        </button>
      </div>
    </div>
  );
}
使用
this.textInput.current.addEventListener('click', this.onDomClick, false);

第二种形式

绑定

render() {
  return (
    <div>
      <p>测试原生事件与合成事件的区别</p>
      <div>
        <button ref="textInput"  //看这里 className="button" onClick={this.onReactClick}>
          点击
        </button>
      </div>
    </div>
  );
}
使用
this.refs.textInput.addEventListener('click', this.onDomClick, false);

第三种形式

绑定

render() {
  return (
    <div>
      <p>测试原生事件与合成事件的区别</p>
      <div>
        <button ref="textInput" className="button" onClick={this.onReactClick}>
          点击
        </button>
      </div>
    </div>
  );
}
使用
const parentDom = ReactDOM.findDOMNode(this.refs.textInput); //看这里  
parentDom.addEventListener('click', this.onDomClick, false);
ReactDOM.findDOMNode(this)  //可以直接获取到当前组件根节点

第四种形式

ref回调形式
class SearchBar extends Component {
   constructor(props) {
      super(props);
      this.txtSearch = null;
      this.setInputSearchRef = e => {
         this.txtSearch = e; //看这里
      }
   }
   render() {
      return (
         <input
            ref={this.setInputSearchRef} /> //看这里
      );
   }
}

第五种形式

内联样式
<input ref={(userName) => {
 this.userName = userName
}} />

相关学习推荐:

以上就是react怎样取得ref的值的详细内容,更多请关注万博manbetx平台中文网其它相关文章!

赞(0) 打赏
未经允许不得转载:万博manbetx平台中文网首页 » React 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏