gpt4 book ai didi

reactjs - React - 相当于 Angular 模板引用变量?

转载 作者:行者123 更新时间:2023-12-04 02:57:53 28 4
gpt4 key购买 nike

在 React 中实现 Angular 的模板引用变量的工作是否有任何替代或解决方法?

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

例如,#firstNameInput 在 <input> 上声明一个 firstNameInput 变量。元素。

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

之后,您可以在模板内的任何位置访问该变量。例如,我将变量作为事件的参数传递。
<button (click)="show(lastNameInput)">Show</button>


show(lastName){
console.log(lastName.value);
}

最佳答案

Angular 模板引用变量的直接对应物是 React ref .

在 React 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} />
);
}
}

它的作用类似于 Angular 引用和 ViewChild , ref 是具有 current 的对象属性是有状态组件的组件实例和非组件的 DOM 元素。

这个角度查询
@ViewChild('barRef', { read: ElementRef })

类似于 React
ReactDOM.findDOMNode(this.barRef)

对于可以以不同方式进行通信的组件,通常应避免使用。

在较旧的 React 版本中,获取 ref 涉及使用函数手动分配它:
<Hi ref={ref => this.hiRef = ref}

哪里 ref是有状态组件的组件实例和非组件的 DOM 元素。

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

关于reactjs - React - 相当于 Angular 模板引用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52037894/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com