reach to(react的refs属性)
导读:refs 字符串形式refs-过时了 // ref key为自命名内容, value为节点 input...
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="点击按钮提示数据" /> <button onClick={this.showData}>点我提示</button> <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="点击按钮提示数据" /> <button onClick={this.showData}>点我提示</button> <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="点击按钮提示数据" /> <button onClick={this.showData}>点我提示</button> </div> ) } }创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!