React组件的Refs
Refs,操作DOM的第二种方法
In the typical React dataflow,propsare 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.
There are a few good use cases for refs:
Avoid using refs for anything that can be done declaratively.
For example, instead of exposingopen()
andclose()
methods on aDialog
component, pass anisOpen
prop to it.
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 theLifting State Upguide for examples of this.
React supports a special attribute that you can attach to any component. Theref
attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.
When theref
attribute is used on an HTML element, theref
callback receives the underlying DOM element as its argument. For example, this code uses theref
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属性
优质内容筛选与推荐>>