Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm fairly new at react.js, so any help is greatly appreciated.

I have this: https://jsfiddle.net/rzjyhf91/

Wherein I have made 2 components: an image and a button.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
151 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

Your actual implementation will depend on your use case, but an updated version of your example that works is at: https://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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...