react.js:删除组件 [英] react.js: removing a component
问题描述
我在react.js上相当新,所以非常感谢任何帮助。
I'm fairly new at react.js, so any help is greatly appreciated.
我有这个: http://jsfiddle.net/rzjyhf91/
其中我制作了2个组件:图像和按钮。
Wherein I have made 2 components: an image and a button.
目标是通过单击按钮删除图像,我使用 unmountComponentAtNode
,但它没有work:
The goal is to remove the image with a click of the button, I use unmountComponentAtNode
for that, but it does not work:
var App = React.createClass({
render: function() {
return (
<div><MyImage /><RemoveImageButton /></div>
);
}
});
var MyImage = React.createClass({
render: function() {
return (
<img id="kitten" src={'http://placekitten.com/g/200/300'} />
);
}
});
var RemoveImageButton = React.createClass ({
render: function() {
return (
<button onClick={this.handleClick}>remove image</button>
)
},
handleClick: function(){
React.unmountComponentAtNode(document.getElementById('kitten'));
}
});
React.render(<App />, document.body);
如何从其他组件中删除反应组件?
How can I remove a react component from another component?
推荐答案
好吧,您似乎应该重新考虑如何处理显示控件。 React是关于隔离组件的,因此,您不应该卸载由父组件安装的组件。相反,你应该使用通过 props
向下传递的回调来完成类似的事情。
Well, it seems you should rethink how the display control is handled. React is all about isolated components, and so, you shouldn't be unmounting a component that is mounted by a parent component. Instead, you should use a callback passed down through props
to accomplish something like that.
你的实际实现将取决于在您的用例上,但有效的示例的更新版本位于: http://jsfiddle.net/nt99zzmp/1/
Your actual implementation will depend on your use case, but an updated version of your example that works is at: http://jsfiddle.net/nt99zzmp/1/
var App = React.createClass({
render: function() {
var img = this.state.showImage ? <MyImage /> : '';
return (
<div>{img}<RemoveImageButton clickHandler={this.removeImage} /></div>
);
},
getInitialState: function() {
return {
showImage: true
};
},
removeImage: function() {
this.setState({ showImage: false });
}
});
var MyImage = React.createClass({
render: function() {
return (
<img id="kitten" src={'http://placekitten.com/g/200/300'} />
);
}
});
var RemoveImageButton = React.createClass ({
render: function() {
return (
<button onClick={this.props.clickHandler}>remove image</button>
)
}
});
React.render(<App />, document.body);
这篇关于react.js:删除组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!