【问题标题】:How Refs works on react 0.14Refs 如何在 react 0.14 上工作
【发布时间】:2016-02-04 03:34:25
【问题描述】:

我在我的 React 0.13 应用程序上使用子渲染方法(在帮助方法中拆分反应组件创建),就像这样。但是我得到了一个错误:

Invariant Violation: addComponentAsRefTo(...): 只有 ReactOwner 可以有 refs。您可能正在向不是在组件的 render 方法中创建的组件添加 ref

那么,如何管理我动态创建的依赖 DOM 的 react 组件,以避免我的主要渲染方法变胖?

任何线索如何将其重构为 0.14 React 版本中的新方法?

module.exports = React.createClass({
displayName: 'Typed',
render: function() {
    var _this = this;

    return (
      React.createElement("div", {
            style: {
                position: 'relative'
            },
            className: 'react-typeahead-container ' + _this.props.className},
        _this._renderInput(),
        _this._renderDropdown(),
        _this._renderAriaMessageForOptions(),
        _this._renderAriaMessageForIncomingOptions()
      )
    );
},
_renderInput: function() {
    var _this = this,
        state = _this.state,
        props = _this.props,
        inputValue = props.inputValue,
        inputValue = props.inputValue,
        className = 'react-typeahead-input',
        inputDirection = getTextDirection(inputValue);

    return (
        React.createElement("div", {
            style: {
                position: 'relative'
            },
            className: "react-typeahead-input-container"},
            React.createElement(Input, {
                ref: "input", //this does not works :(
                role: "combobox"
            )
        )
    );
},

【问题讨论】:

  • 顺便问一下,你需要 React 模块吗?
  • 好的兄弟,之前需要 React 模块,但是谢谢
  • 我没有面对它,但here 是类似的问题。希望对你有帮助

标签: javascript reactjs


【解决方案1】:

作为this JSFiddle shows,您上面的代码可以正常工作(稍作修改,使其按原样运行)。有一个小的语法错误;包含属性的对象缺少右花括号:

React.createElement(Input, {
    ref: "input", //this does not works :(
    role: "combobox"
) // <-- should be })

【讨论】:

    【解决方案2】:

    据我了解,ref 应该是接收被引用元素的回调方法。在这种情况下,input。然后您可以将其存储在state 或其他人中并引用它。当它有效时,引用的 DOM 节点将被渲染。

    【讨论】:

    • 这是在 0.13 中引入的,是可选的。基于字符串的引用应该仍然有效(至少对于基于 createClass 的组件)
    猜你喜欢
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多