export class Child extends React.Component{
unmount() {
const node = ReactDOM.getDOMNode(this);
ReactDOM.unmountComponentAtNode(node );
}
render() {
return <button onClick={this.unmount.bind(this)}>Unmount</button>
}
}
对于上面的示例组件,是否可以使用unmountComponentAtNode
?
答案 0 :(得分:0)
这不是反应的方式。 卸载元素的最佳方法是告诉父元素从父元素的渲染子元素中删除子元素。
看看这个例子。 这里我们有CardContainer类和CardItem类.CardItem项类有一个删除自己按钮。此方法将事件发送到父容器,以从呈现的子项中删除它自己。
const carddata = [
{key:1 ,name: 'Card A',visible:true},
{key:2 ,name: 'Card B',visible:true}
];
class CardItem extends React.Component {
constructor(props){
super(props)
this.handleClick=this.handleClick.bind(this);
}
componentWillUnmount(){
console.log('unmount')
}
handleClick(){
this.props.destroy(this.props.id)
}
render(){
return(<div>
Card
<button onClick={this.handleClick} >delete</button>
</div>)
}
}
class CardContainer extends React.Component {
constructor(props){
super(props)
this.state = {data: carddata};
this.destroy = this.destroy.bind(this);
}
destroy(elementKey){
console.log(elementKey)
debugger
let result = this.state.data.filter(item=> item.key !==elementKey);
this.setState({data: result});
}
render(){
return (<div>
Card Container
{this.state.data.map((card,index) => {
return <CardItem key={card.key} id={card.key} name={card.name} destroy={this.destroy}/>
})
}
</div>)
}
}
答案 1 :(得分:0)
React应用程序始终是一个组件组合,或者用不同的词语 - 组件树。这意味着每个组件都有父组件,它呈现它,它只是根组件的虚假语句,我们大多将它命名为 App ,但我们不会在那个问题中谈论它。最重要的是,我们可以说一个需要卸载的组件总是有一个父组件。
正如我们在第一段中所做的那样,卸载React组件的正确方法是从父组件中的render方法中删除它。它可以通过多种方式完成,最简单的只是一个条件组件渲染,如:
this.state.show
上面的示例将 IAmParentComponent 显示为包含状态的容器组件,如果true
为true
, YourChildComponentToUnmount 将呈现,将在之后取消状态从false
更改为{{1}}。
使用回调返回代码,回调应该通过props发送到组件中,而父组件应该执行与从渲染树中删除组件相关的状态更改,究竟将启动组件的卸载阶段,最后组件将从UI中删除。
总之,组件卸载应该在其上面的组件的责任中,组件不应该自行卸载。