gpt4 book ai didi

javascript - 如何访问渲染中设置的引用

转载 作者:行者123 更新时间:2023-12-03 13:32:00 25 4
gpt4 key购买 nike

嗨,我有以下某种代码:

class First extends Component {
constructor(props){super(props)}

myfunction = () => { this.card //do stuff}

render() {
return(
<Component ref={ref => (this.card = ref)} />
)}
}

为什么我无法访问myfunction中的card。它告诉我它是未定义的。我尝试在构造函数中设置 this.card = React.createRef(); ,但这也不起作用。

最佳答案

您已经快到了,您的子组件很可能没有使用 forwardRef,因此出现错误(来自 React docs )。默认情况下,ref(与key类似)不能直接访问:

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

// ☝️ now you can do <MyComponent ref={this.card} />

ref 最终是一个 DOMNode,应该这样对待,它只能引用将要渲染的 HTML 节点。在一些较旧的库中,您会看到它为 innerRef,它也可以在不需要 forwardRef 的情况下工作,以防它让您感到困惑:

const MyComponent = ({ innerRef, children }) => (
<button ref={innerRef}>
{children}
</button>
));

// ☝️ now you can do <MyComponent innerRef={this.card} />

最后,如果它是您创建的组件,您需要确保通过 forwardRef (或 innerRef)等效项传递引用。如果您使用的是第三方组件,您可以测试它是否使用 refinnerRef。如果没有,将其包裹在 div 周围,尽管并不理想,但可能就足够了(但并不总是有效):

render() {
return (
<div ref={this.card}>
<MyComponent />
</div>
);
}

现在,对 refs 和生命周期方法进行一些解释,这可能会帮助您更好地理解上下文。

渲染不保证 refs 已设置:

这是一种先有鸡还是先有蛋的问题:您希望组件使用指向节点的ref执行某些操作,但 React 没有创建节点本身。那么我们能做什么呢?

有两个选项:

1) 如果您需要传递引用来渲染其他内容,请首先检查它是否有效:

render() {
return (
<>
<MyComponent ref={this.card} />
{ this.card.current && <OtherComponent target={this.card.current} />
</>
);
}

2) 如果您希望实现某种副作用,componentDidMount 将保证设置 ref:

componentDidMount() {
if (this.card.current) {
console.log(this.card.current.classList);
}
}

希望这能让事情变得更清楚!

关于javascript - 如何访问渲染中设置的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60581688/

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