【问题标题】:Can't add a ref to an object which will be reloaded by setState无法将 ref 添加到将由 setState 重新加载的对象
【发布时间】:2017-07-19 06:07:15
【问题描述】:

我只是想为对象添加一个引用,因为我必须清除它的值。 我这样写:

this.code = (
    <div className="form-group">
          <label className="form-label" htmlFor="target">Target</label>
          <input className="input" onChange={this.handleChange.bind(this)} ref="textbox" id="target" type="text" placeholder="Target" />
        </div>
);
this.setState(this.state);

并得到如下错误:

Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded

我想做的很简单:如果我点击一个按钮,现有的表单将被清除,并且会出现其他表单。为此,我尝试使用setState 方法。这是错误的方法吗?

【问题讨论】:

标签: javascript html reactjs jsx


【解决方案1】:

只有 ReactOwner 可以有 refs。您可能正在将 ref 添加到 不是在组件的 render 方法中创建的组件, 或者你加载了多个 React 副本

根据 React 文档:

This usually means one of two things:

1. You are trying to add a ref to an element that is being created outside of a component's render() function.
2. You have multiple (conflicting) copies of React loaded (eg. due to a misconfigured NPM dependency)

你的情况似乎是第一个,你试图在你的渲染函数之外创建文档对象。

解决方案是从返回文档对象的渲染函数中调用一个函数

renderInput = () => {
    return (
        <div className="form-group">
          <label className="form-label" htmlFor="target">Target</label>
          <input className="input" onChange={this.handleChange.bind(this)} ref={(ref) => this.textbox = ref} id="target" type="text" placeholder="Target" />
        </div>
    )
}
render() {
   return (
       <div>
            {this.renderInputForm()}
      </div>
   )
}

附: React 建议对引用使用回调方法而不是字符串引用。检查这个答案:

In React .js: is there any function similar like document.getElementById() in javascript ? how to select certain object?

同样是Invalid Refs:

只有 ReactOwner 可以有 refs。这通常意味着你正在尝试 将 ref 添加到没有所有者的组件(即 不是在另一个组件的渲染方法中创建的)。尝试 将此组件呈现在一个新的顶级组件中,该组件 将持有参考。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 2011-08-22
    • 1970-01-01
    • 2020-10-17
    • 2020-11-21
    • 1970-01-01
    相关资源
    最近更新 更多