React的ref是啥?强力一波

栏目: 服务器 · 发布时间: 6年前

内容简介:理解:通过指定ref获得你想操作的元素,然后进行修改<input ref="myInput" />回调函数将接收当前的DOM元素作为参数,然后存储一个指向这个DOM元素的引用。那么在示例代码中,我们已经把input元素存储在了this.textInput中,在focus函数中直接使用原生DOM API实现focus聚焦。

React ref

理解:通过指定ref获得你想操作的元素,然后进行修改

string 使用方法

<input ref="myInput" />

var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = input.getBoundingClientRect();

ref作为回调函数的方式去使用

class Input extends Component {
    constructor(props){
        super(props);
    }
    
    focus = () => {
        this.textInput.focus();
    }
    
    render(){
        return (
            <div>
                <input ref={(input) => { this.textInput = input }} />
            </div>
        )
    }
}

input参数是哪来的

回调函数将接收当前的DOM元素作为参数,然后存储一个指向这个DOM元素的引用。那么在示例代码中,我们已经把input元素存储在了this.textInput中,在focus函数中直接使用原生DOM API实现focus聚焦。

回调函数什么时候被调用

答案是当组件挂载后和卸载后,以及ref属性本身发生变化时,回调函数就会被调用。

不能在无状态组件中使用ref

理解:class组件-对象组件-有实例 无状态组件-函数组件-无实例

上代码:

function MyFunctionalComponent() {
    return <input />;
}

class Parent extends React.Component {
    render() {
        return (
            <MyFunctionalComponent
                ref={(input) => { this.textInput = input; }} />
        );
    }
}

父组件的ref回调函数可以使用子组件的DOM。

function CustomTextInput(props) {
    return (
        <div>
            <input ref={props.inputRef} />
        </div>
    );
}

class Parent extends React.Component {
    render() {
        return (
            <CustomTextInput
                inputRef={el => this.inputElement = el}
            />
        );
    }
}

原理就是父组件把ref的回调函数当做inputRefprops传递给子组件,然后子组件<CustomTextInput>把这个函数和当前的DOM绑定,最终的结果是父组件<Parent>的this.inputElement存储的DOM是子组件<CustomTextInput>中的input。

同样的道理,如果A组件是B组件的父组件,B组件是C组件的父组件,那么可用上面的方法,让A组件拿到C组件的DOM。

理念

Facebook非常不推荐会打破组件的封装性的做法,多级调用确实不雅,需要考虑其他更好的方案去优化


以上所述就是小编给大家介绍的《React的ref是啥?强力一波》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web 2.0 Architectures

Web 2.0 Architectures

Duane Nickull、Dion Hinchcliffe、James Governor / O'Reilly / 2009 / USD 34.99

The "Web 2.0" phenomena has become more pervasive than ever before. It is impacting the very fabric of our society and presents opportunities for those with knowledge. The individuals who understand t......一起来看看 《Web 2.0 Architectures》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

MD5 加密
MD5 加密

MD5 加密工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具