gpt4 book ai didi

reactjs - 如何获取组件当前的原生元素?

转载 作者:行者123 更新时间:2023-12-05 07:48:48 26 4
gpt4 key购买 nike

我知道你可以调用 React.findDOMNode(this),但是还有其他方法吗?我想知道是否保留了引用(并且在安装组件时显然可用)。

最佳答案

一段时间以来,React 和 refs 一直是一个移动的目标。

Facebook has said字符串引用已弃用。

If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.

当前的最佳实践是回调引用。理想情况下,您将使用 setState 管理组件状态。但是,如果您需要使用其他库或动画,则需要引用。另请参阅:ReactDOM.findDOMNode()

JSFiddle

const HowdyPardner = React.createClass({
_getHeaderEl: function( el ) {
this.headerEl = el;
},
componentDidMount() {
this.headerEl.textContent = 'YEEHAW';
},
render: function() {
return (
<h1 ref={this._getHeaderEl}>Howdy Pardner!</h1>
);
}
});

关于reactjs - 如何获取组件当前的原生元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38155131/

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