react的refs属性

  • react的refs属性已关闭评论
  • 68 次浏览
  • A+
所属分类:Web前端

refs

字符串形式refs-过时了

// ref key为自命名内容, value为节点 input         class Demo extends React.Component {             showData = () => {                 // 拿到的是真实DOM                 const { input1 } = this.refs;                 alert(input1.value);             }             showData2 = () => {                 const { input2 } = this.refs;                 alert(input2.value);             }             render() {                 return (                     <div>                         <input ref="input1" type="text" placeholder="点击按钮提示数据" /> &nbsp;                         <button onClick={this.showData}>点我提示</button>&nbsp;                         <input onBlur={this.showData2} ref="input2" type="text" placeholder="失去焦点提示" />                     </div>                 )             }         } 

回调函数形式refs

// 回调函数中c是当前节点,this.input1的Demo实例的属性         class Demo extends React.Component {             showData = () => {                 // 拿到的是真实DOM                 const { input1 } = this;                 alert(input1.value);             }             showData2 = () => {                 const { input2 } = this;                 alert(input2.value);             }             // 直接调用             showInfo = (c) => {                 this.input2 = c;             }             render() {                 return (                     <div>                         <input ref={c => this.input1 = c} type="text" placeholder="点击按钮提示数据" /> &nbsp;                         <button onClick={this.showData}>点我提示</button>&nbsp;                         <input ref={this.showInfo} onBlur={this.showData2} type="text" placeholder="失去焦点提示" />                     </div>                 )             }         } 

createRef

        class Demo extends React.Component {             // React.createRef 调用后可以返回一个容器,该容器可以存储被ref所表示的节点             // 即创建一个容器,将input节点放入容器中             // 一个容器存一个节点             myRef = React.createRef();             showData = () => {                 // 拿到的是真实DOM                 const value = this.myRef.current.value;                 alert(value);             }             render() {                 return (                     <div>                         <input ref={this.myRef} type="text" placeholder="点击按钮提示数据" /> &nbsp;                         <button onClick={this.showData}>点我提示</button>&nbsp;                     </div>                 )             }         }