gpt4 book ai didi

javascript - 使用 React.cloneElement() 保存的引用

转载 作者:数据小太阳 更新时间:2023-10-29 06:14:06 25 4
gpt4 key购买 nike

我不明白 React official docs 中所写陈述的意义:

cloneElement()

React.cloneElement(
element,
[props],
[...children]
)

Clone and return a new React element using element as the starting point. The resulting element will have the original element’s props with the new props merged in shallowly. New children will replace existing children. key and ref from the original element will be preserved.

React.cloneElement() is almost equivalent to:

<element.type {...element.props} {...props}>{children}</element.type>

However, it also preserves refs. This means that if you get a child with a ref on it, you won’t accidentally steal it from your ancestor. You will get the same ref attached to your new element.

让我感到困惑的是声明这意味着如果你得到一个带有 ref 的 child ,你就不会不小心从你的祖先那里偷走它。您将获得附加到新元素的相同引用。

如果我的理解是好的,即使父组件被克隆,指向父组件中子元素的 ref 也会被保留。所以在 React.cloneElement(Parent) 之后,有两个单独的 Parents(里面有相同的深度值,包括 ref),并且都分别有 refs,并且这些 refs 指向同一个 Child。我正确吗?

那么 ancestor 有什么用呢?在这种情况下,祖先是什么?

最佳答案

为了举例说明文档似乎在说明什么,让我们考虑一个呈现组件的组件应用程序 Main它有两个 child Home 和 Dashboard,它为其指定了 refs

class App extends React.Component {
constructor(props) {
super(props);
this.homeRef = React.createRef();
this.dashboardRef = React.createRef();
}
render() {
return (
<Main>
<Home ref={this.homeRef} key={'Home'}/>
<Dashboard ref={this.dashboardRef} key={'Dashboard'}/>
</Main>
)
}
}

现在主要组件克隆子元素以向其子元素添加 Prop onClick,

class Main extends React.Component {
onClick = () => {}
render() {
return (
<div>
{/* Some content here */}
{React.Children.map(this.props.children, child => {
return React.cloneElement(child, {onClick: this.onClick})
})}
</div>
)
}
}

现在 Main组件克隆它的 child

React.cloneElement(child, {onClick: this.onClick})

在我们的例子中是主页和仪表板组件,如果 cloneElement忽略 keyref由 App 组件传递给它们,App 组件将无法访问它呈现的这些子项。因此 React.cloneElement 会保留传递给元素的 refs 和键,即使它们是在子渲染函数中克隆的。

The component created by createdElement is cloned child, and what is used by <Main> is the cloned child, then what does ref in <App> point? Original child, or cloned child?

Does the phrase accidentally steal means something like forbidden access

仅当元素在 DOM 中呈现时,对元素的引用才有意义。在上面的例子中,原始元素没有被渲染,但是克隆的元素被渲染了。如果 React 没有将相同的 ref 分配给在 DOM 中呈现的克隆组件,App 组件就不会与任何重要的东西进行交互。此外,如果您决定同时渲染原始子项和克隆子项,则 ref 将指向克隆子项。

Demo illustrating the above

P.S. CloneElement 不用于克隆组件,而不是渲染 JSX 实例,主要用于向

children component rendered from elsewhere

希望上面的例子能说明场景

关于javascript - 使用 React.cloneElement() 保存的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54606845/

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