react的refs属性

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

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>
                )
            }
        }
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6