javascript - 克隆已经安装的组件

标签 javascript reactjs

我正在尝试构建一个使用拖放行为的应用程序,并且被拖动的组件需要克隆到 DOM 中的其他位置。由于该组件已经安装,尝试再次安装它会导致浏览器挂起。

尝试使用 cloneWithProps 会导致无法读取未定义的属性“defaultProps” 错误。

这是一个测试用例:

var TestCase = React.createClass({
  getInitialState () {
    return {
      draggingItem: null
    }
  },

  render () {
    return <div>
      <ExampleComponent onClick={this.setDraggingItem} />
      {this.state.draggingItem}
    </div>
  },

  setDraggingItem (component) {
    // This gives `Cannot read property 'defaultProps' of undefined`
    //React.addons.cloneWithProps(component)

    // This crashes the browser
    //this.setState({ draggingItem: component })
  }
})

var ExampleComponent = React.createClass({
  render () {
    return <div onClick={this.handleOnClick}>Hello World</div>
  },

  handleOnClick (event) {
    this.props.onClick(this)
  }
})

React.render(<TestCase />, document.body)

当然,我可以简单地在 setDraggingItem 中克隆 component.getDOMNode(),但看起来渲染组件或调用 cloneWithProps 应该工作?

最佳答案

创建元素需要的两件事是:组件类(例如ExampleComponent)及其 Prop 。 cloneWithProps 只能在渲染中使用,并且只能与来自在另一个组件的渲染中创建的 props 的元素一起使用。您不应该保存元素,也不应该将它们传递给渲染中的其他组件。相反,您传递对象( Prop )和组件类。

由于您首先需要知道渲染它的 Prop 和组件类,因此您可以在 TestCase 中处理所有这些。

var TestCase = React.createClass({
  getInitialState () {
    return {
      draggingItem: null,
      draggingItemProps: null
    }
  },

  render () {
    return <div>
      <ExampleComponent onClick={this.setDraggingItem.bind(null, 
      /* the component class */         ExampleComponent, 
      /* the props to render it with */ null
      )} />
      { 
        this.state.draggingItem && React.createElement(
          this.state.draggingItem, 
          this.state.draggingItemProps
        )
      }
    </div>
  },

  setDraggingItem (component, props, event) {
    this.setState({ draggingItem: component, draggingItemProps: props })
  }
});

var ExampleComponent = React.createClass({
  render () {
    return <div onClick={this.handleOnClick}>Hello World</div>
  },
  // just defer the event
  handleOnClick (event) {
    this.props.onClick(event)
  }
});

如果您希望使这些在 TestCase 组件之外有效,请确保 props 中没有任何函数绑定(bind)到 TestCase。还要确保其中没有包含 React 元素的 child Prop 。如果子项相关,请提供重新创建它们所需的 {componentClass,props} 结构。

很难说出您的实际需求是什么,但希望这足以让您开始。

关于javascript - 克隆已经安装的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27447694/

相关文章:

javascript - 如何在 Mocha 测试用例中使用 setTimeout() 函数?

javascript - 调用打印函数后页面卡住

javascript - 使用 ReactPDF 加载 React 时出现 PDF 错误

javascript - 如何在循环中使用 Fetch 查询?

reactjs - react 使用历史: Hooks can only be called inside the body of a function component

javascript - 不断收到“无法读取属性错误”

javascript - 编译多个 hash.location

javascript - Angular 资源更新不起作用

javascript - 是否可以使用 jquery 选择样式元素?

javascript - 尝试使用自定义内容创建 React 抽屉导航