In Facebook's documentation on refs
:
Don’t Overuse
Refs
Your first inclination may be to use refs to “make things happen” in your app. If this is the case, take a moment and think more critically about wherestate
should be owned in the component hierarchy. Often, it becomes clear that the proper place to “own” that state is at a higher level in the hierarchy. See theLifting State Up
guide for examples of this.
在我当前的 React 应用程序中,我有几个要根据条件修改的 div
节点。这些 div 节点是在 render()
的链式 returns
深处创建的。我当然不能使用 Document.queryselector()。我想不出别的了。
文档也试图用文章“提升状态”来解释,但我不明白。有人可以阐明这一点吗? (ELI5
如果可以的话。)
最佳答案
提升状态意味着子组件引发事件而不是自己处理状态变化。在React docs他们从每个组件管理自己的状态 (handleChange) 开始。再往下,他们通过添加 onTemperatureChange
Prop 来提升状态。现在,子级将状态更改委托(delegate)给它们最接近的公共(public)父级 Calculator
。 Calculator
更改状态并通过 props 向下推送新值。
我只在需要调用 DOM 元素上的特定函数时才使用 refs,使用 focus()
到目前为止,这是我的应用程序中最常见的用法。这SO answer有一个很好的例子,因为链接不好所以复制到这里:
class App extends React.Component{
componentDidMount(){
this.nameInput.focus();
}
render() {
return(
<div>
<input
defaultValue="Won't focus"
/>
<input
ref={(input) => { this.nameInput = input; }}
defaultValue="will focus"
/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
另请务必阅读 answer below the linked answer , autoFocus
是安装时聚焦的正确答案,但在某些时候您肯定希望动态聚焦元素。
关于javascript - 为什么我们不应该使用 ref?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51344510/