代码之家  ›  专栏  ›  技术社区  ›  Abdul Rafay

反应-相当于角度模板参考变量?

  •  1
  • Abdul Rafay  · 技术社区  · 7 年前

    在Angular中,模板引用变量通常是对模板中的DOM元素的引用。使用哈希符号(#)声明引用变量。

    例如,firstNameInput在 <input> 元素。

    <input type="text" #firstNameInput>
    <input type="text" #lastNameInput>
    

    之后,您可以在模板中的任何位置访问变量。例如,我将变量作为事件的参数传递。

    <button (click)="show(lastNameInput)">Show</button>
    
    
    show(lastName){
        console.log(lastName.value);
    }
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   Estus Flask    7 年前

    与角度模板参考变量直接对应的是 React ref

    反应16.3 createRef

    class Some extends React.Component {
      fooRef = React.createRef();
      barRef = React.createRef();
    
      componentDidMount() {
        console.log(this.fooRef.current instanceof Node); // true
        console.log(this.barRef.current instanceof Bar); // true
      }
    
      render() {
        return (
          <input type="text" ref={this.fooRef}>
          <Bar ref={this.barRef} />
        );
      }
    }
    

    它的作用类似于角度参考和 ViewChild current 属性,该属性是有状态组件的组件实例,而非组件的则是DOM元素。

    @ViewChild('barRef', { read: ElementRef })
    

    类似于反应

    ReactDOM.findDOMNode(this.barRef)
    

    在较旧的React版本中,获取ref涉及到使用函数手动分配它:

    <Hi ref={ref => this.hiRef = ref}
    

    ref

    在React中,ref相对较少使用,通过props传递回调函数通常是组件之间更可取的通信方式(将回调作为组件传递 @Input ,以角度表示)。

        2
  •  2
  •   Maciej Wojsław    7 年前