Refs,操作DOM的第二种方法
Refs and the DOM
In the typical React dataflow, props are the only way that parent components interact with their children. To modify a child, you re-render it with new props. However, there are a few cases where you need to imperatively modify a child outside of the typical dataflow. The child to be modified could be an instance of a React component, or it could be a DOM element. For both of these cases, React provides an escape hatch.
When to Use Refs
There are a few good use cases for refs:
- Managing focus, text selection, or media playback.
- Triggering imperative animations.
- Integrating with third-party DOM libraries.
Avoid using refs for anything that can be done declaratively.
For example, instead of exposing open()
and close()
methods on a Dialog
component, pass an isOpen
prop to it.
Don't Overuse Refs
Your first inclination may be to use refs to "make things happen" in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to "own" that state is at a higher level in the hierarchy. See the Lifting State Up guide for examples of this.
Adding a Ref to a DOM Element
React supports a special attribute that you can attach to any component. The ref
attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.
When the ref
attribute is used on an HTML element, the ref
callback receives the underlying DOM element as its argument. For example, this code uses the ref
callback to store a reference to a DOM node:
changeLogin(name){ //使用传参的方式传递值 this.setState({username:name}); //操作DOM的第一种方式,类似于原生JS的方式 // var loginBtn=document.getElementById('loginBtn'); //console.log(loginBtn); // ReactDOM.findDOMNode(loginBtn).style.color='red'; //操作DOM的第二种方式,更React,性能更优,推荐 console.log(this.refs.loginBtn); this.refs.loginBtn.style.color='green'; } return( <div> <input id='loginBtn' type='button' ref='loginBtn' value='登录' onClick={this.changeLogin.bind(this,'rain')} /> </div> )
step-1 在html元素中添加ref属性,并为其赋值:
<input type='button' ref='loginBtn' value='登录' onClick={this.changeLogin.bind(this,'rain')} />
step-2 在自定义的function中使用下列语法进行DOM操作
this.refs.loginBtn.style.color='green'; //为获取到的loginBtn设置颜色
注意:
1.Refs是访问到组件内部DOM节点唯一可靠的方法
2.Refs会自动销毁对子组件的引用
3.不要在render或render之前对Refs进行调用(在React生命周期内调用也会引起性能问题)
4.不要滥用Refs,否则会引起性能问题,建议使用setState属性