这次学习用到了refs,遇到了点问题,所以去看了一下官方文档,本文是跟据官方文档中介绍的refs总结其中的用法,其实一句React的实现原理,组件的状态变化都是依据数据流的流动而改变的,从原则上讲获取组件实例的状况是不应该出现的,但是情况也不是绝对的,有的时候还是有这样的需求的,以下内容是由微蓝经验网用户发布干货:Refs to components,希望对于用户有一定帮助,为朋友进行解决疑惑,如若想了解更多相关内容,可以向底部移动了解更多与本教程文章相关解决经验方法!
1,The Ref returned from ReactDOM,render
从ReactDOM,render方法返回的ref
我们都知道,当我们的组件结构全部搭建完成,渲染我们的顶级组件时用的就是这个方法,但可能大家不知道的是,这个方法返回的就是我们顶级组件的组件实例对象,var myComponent = ReactDOM,render(
2,The Ref Callback Attribute
当我们渲染一个组件时,可以给组件添加ref属性,我们给这个属性添加一个回调方法,当组件渲染(mounted)完毕时,就会调用这个回调函数,render: function() {
return (
3,The Ref String Attribute
ref的另外一个使用方法就是给ref属性一个字符串,相当于给组件起了一个名字,渲染完成后,就可以使用this,ref,name的方式获取组件类的实例,同样,如果是div一类的,获取到的是dom节点,如果是自定义组件,获取到的是组件类实例,var App = React,createClass({ componentDidMount : function(){ var node1 = this,refs,myinput; var node2 = ReactDOM,findDOMNode(this,refs,myson); }, render: function() { return (
下面是文档中的一个例子:
var MyComponent = React,createClass({ handleClick: function() { // Explicitly focus the text input using the raw DOM API, if (this,myTextInput ,== null) { this,myTextInput,focus(); } }, render: function() { // The ref attribute is a callback that saves a reference to the // component to this,myTextInput when the component is mounted, return (
Refs are a great way to send a message to a particular child instance in a way that would be inconvenient to do via streaming Reactive props and state,如果你觉得依靠互动性的props和state向某个特定子实例中传递消息不是很好的方式的话,refs是一个很好的解决办法,They should, however, not be your go-to abstraction for flowing data through your application,ref不应该成为你的应用中抽象的传递数据的方法,By default, use the Reactive data flow and save refs for use cases that are inherently non-reactive,所以,在应用互动数据流的同时,refs适合于那些非互动性的实例。
补充一点:ref在stateless function中没法用的,什么是stateless function呢?
function HelloMessage(props) { return
微蓝网部分素材(图片、视频、音频等)来自于网络,不代表本站立场,以上素材或内容仅代表作者个人观点,因此产生相关问题作者本人负责,本站将不承担任何法律责任! 如有问题请进行侵权投诉
© 2025 VLPOS.com 版权所有 微蓝网 ICP备案号:黑ICP备20003952号-1
黑公网安备 23012602000120号