gpt4 book ai didi

javascript - React forwardRef 含义

转载 作者:行者123 更新时间:2023-11-29 22:55:12 26 4
gpt4 key购买 nike

我不明白这是什么意思:

const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));

如果我能做到:

function FancyButton(props) {
return (
<button className="FancyButton" ref={props.ref}>
{props.children}
</button>
);
}

最佳答案

来自文档

Ref forwarding is a technique for automatically passing a ref through a component to one of its children.

Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.

针对您的问题

I don't get what's the point of this: If i can do this:.

您可以选择第一种方法或第二种方法

例子

// EmailInput wraps an HTML `input` and adds some app-specific styling.
const EmailInput = React.forwardRef((props, ref) => (
<input ref={ref} {...props} type="email" className="AppEmailInput" />
));

class App extends Component {
emailRef = React.createRef();

render() {
return (
<div>
<EmailInput ref={this.emailRef} />
<button onClick={() => this.onClickButton()}>
Click me to focus email
</button>
</div>
);
}

// `this.emailRef.current` points to the `input` component inside of EmailInput,
// because EmailInput is forwarding its ref via the `React.forwardRef` callback.
onClickButton() {
this.emailRef.current.focus();
}
}

对我来说 fowardRef 并不需要太多,因为我们总是可以使用另一种方法传递 ref

您可以在 here 阅读更多内容

关于javascript - React forwardRef 含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56751609/

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