作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
根据 React.js 官方文档,以下代码是回调引用的示例。
function CustomTextInput(props) {
return (
<div>
<input ref={props.inputRef} />
</div>
);
}
class Parent extends React.Component {
componentDidMount(props) {
//Here, this.inputElement in Parent will be set to the DOM node corresponding to the element in the CustomTextInput
console.log(this.inputElement);
}
render() {
return (
<CustomTextInput
inputRef={el => this.inputElement = el}
/>
);
}
}
这里Parent中的this.inputElement会被设置为CustomTextInput中元素对应的DOM节点。
在转发 ref 的情况下,根据官方文档,
const FancyButton = React.forwardRef((props, ref) => {
return (
<button ref={ref} className="FancyButton" data-name="My button">
{props.children}
</button>
);
});
//Parent Component
class FancyButtonWrapper extends React.Component {
constructor(props) {
super(props);
this.buttonRef = React.createRef();
}
componentDidMount(props) {
//Here this.ref will point to button element. Because of this reason, ref.current will give the value of button.
console.log(this.buttonRef.current.getAttribute("data-name"));
}
render() {
return (
//Here we are passing the ref to the child component.
<FancyButton ref={this.buttonRef} data-attr="Hello">
Click me!{" "}
</FancyButton>
);
}
}
在这里,在这种情况下,this.ref 将指向按钮元素。由于这个原因,ref.current 将给出 button 的值。
forwardRef 和 callbackRefs 有区别吗?在这两种情况下,我们都可以从父节点访问子节点的引用。
最佳答案
我不是专家,但这里有一些值得思考的问题:- 回调 refs 在我们需要动态设置 refs 时使用。- Forward refs 通常在需要访问子引用时使用。
关于reactjs - React 中的 forwardingRef 与回调 refs 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59045294/
根据 React.js 官方文档,以下代码是回调引用的示例。 function CustomTextInput(props) { return ( ); }
我是一名优秀的程序员,十分优秀!