gpt4 book ai didi

javascript - 克隆一个已经挂载的组件

转载 作者:行者123 更新时间:2023-11-29 21:54:03 26 4
gpt4 key购买 nike

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

尝试使用 cloneWithProps 会导致 Cannot read property 'defaultProps' of undefined 错误。

这是一个测试用例:

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 只能在 render 中使用,并且只能用于来自在另一个组件的渲染中创建的 props 的元素。您不应该保存元素,或者将它们传递给渲染中的其他组件以外的其他元素。相反,您传递对象( Prop )和组件类。

由于您首先需要知道 props 和组件类来渲染它,因此您可以在 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 组件之外有效,请确保没有任何函数绑定(bind)到 props 中的 TestCase。还要确保其中没有带有反应元素的 child Prop 。如果子项相关,请提供重新创建它们所需的 {componentClass,props} 结构。

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com