javascript - 为什么我们不应该使用 ref?

标签 javascript reactjs

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 where state 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 the Lifting State Up guide for examples of this.

在我当前的 React 应用程序中,我有几个要根据条件修改的 div 节点。这些 div 节点是在 render() 的链式 returns 深处创建的。我当然不能使用 Document.queryselector()。我想不出别的了。

文档也试图用文章“提升状态”来解释,但我不明白。有人可以阐明这一点吗? (ELI5 如果可以的话。)

最佳答案

提升状态意味着子组件引发事件而不是自己处理状态变化。在React docs他们从每个组件管理自己的状态 (handleChange) 开始。再往下,他们通过添加 onTemperatureChange Prop 来提升状态。现在,子级将状态更改委托(delegate)给它们最接近的公共(public)父级 CalculatorCalculator 更改状态并通过 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/

相关文章:

javascript - reactjs:未捕获类型错误:无法读取未定义的属性 'value'

javascript - 如何在ReactJS中实现带有受控组件的动态表单?

javascript - 在 JSX 中将字符串中的逗号拆分为 <br/>

reactjs - 在 React 自定义 Hook 中 onChange 时验证输入的最佳实践?

javascript - 将javascript中的长数字格式化为正确的单位的最简单方法?

javascript - 如何通过 props 传递字符串,然后将其用作 React Native 中组件标签中的值?

javascript - 使用文本文件而不是数组?

javascript - 使用 ng-repeat 动态加载指令

css - 如何使用伪类在悬停时创建 mui 过渡?

javascript - 将参数传递给 React 组件