React从入门到精通系列之(14)refs和DOM元素

前端之家收集整理的这篇文章主要介绍了React从入门到精通系列之(14)refs和DOM元素前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

十四、refs和DOM元素

在典型的React数据流中,props是父组件与其子组件交互的唯一方式。 要修改子组件,需要使用一个新的props进行重新渲染。

但是,在某些情况下,您需要在典型数据流之外强制修改子组件。 要修改的子组件可以是React组件实例,也可以是DOM元素。 对于这两种情况,React提供了一个以下这样的功能

通过ref属性设置回调函数

React提供可以附加到任何组件的特殊属性ref属性接受一个回调函数,回调函数将在组件被挂载或卸载后立即执行。

当在HTML元素上使用ref属性时,ref回调函数接收一个基础的DOM元素作为其参数。 例如,此代码使用ref回调函数来存储对DOM节点的引用:

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3.  
  4. class CustomTextInput extends React.Component {
  5. constructor(props) {
  6. super(props);
  7. this.focus = this.focus.bind(this);
  8. }
  9.  
  10. focus() {
  11. // textInput是一个标准的DOM元素
  12. this.textInput.focus();
  13. }
  14.  
  15. render() {
  16. return (
  17. <div>
  18. <input type="text" ref={input => {
  19. this.textInput = input;
  20. }}/>
  21. <input type="button" value="选中上面的text input" onClick={this.focus}/>
  22. </div>
  23. );
  24. }
  25. }
  26. ReactDOM.render(
  27. <CustomTextInput/>,document.getElementById('root')
  28. );

当组件装载(mounting)时,React将使用DOM元素调用ref回调函数,并在卸载时用null调用它。

使用ref回调函数是为类设置一个属性来访问DOM元素的常见模式。 如果您目前正在使用this.refs.myRefName来访问DOM引用的话,我会建议你使用此模式。

当在自定义组件上使用ref属性时,ref回调接收组件的已装入的组件实例作为其参数。 例如,如果我们想要包装上面的CustomTextInput来模拟它在装载(mounting)后立即被点击:

  1. class AutoFocusTextInput extends React.Component {
  2. componentDidMount() {
  3. this.textInput.focus();
  4. }
  5. render() {
  6. return (
  7. <CustomTextInput ref={input => {this.textInput = input; }} />
  8. );
  9. }
  10. }

您不能在功能性组件上使用ref属性,因为它们没有实例。 但是,您可以使用功能性组件的render函数内的ref属性

  1. function CustomTextInput(props) {
  2. // 这里必须提前顶一个textInput,只有这样才可以正常执行ref回调函数
  3. let textInput = null;
  4. function click() {
  5. textInput.focus();
  6. }
  7. return (
  8. <div>
  9. <input type="text" ref={input => { textInput = input; }} />
  10. <input type="button" value="选中这个输入框" onClick={this.click} />
  11. </div>
  12. );
  13. }

不要过度使用ref

你的第一个倾向可能是使用refs在你的应用中“make things happen”

如果是这种情况,你必须花一点时间,关键去考虑在组件层次结构中应该拥有什么状态。通常,在层次结构中处于更高级别的组件“拥有”状态是一个让一切便清除的最适当位置。 有关示例,请参阅本系列的第10篇《提升state》。

猜你在找的React相关文章