Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

reactjs - React.render replace container instead of inserting into

I'm gradually replacing some Backbone views with React.

My React View:

<div id="reactViewContent">Rendered By React</div>

I need to render the React view below other html elements without replacing them.

<div id="somestuff">
  <div id="anotherView">Other stuff not to delete</div>
  <div id="placeholderForReactView"></div>
</div>

I'd like that my method could replace the placeholder instead of inserting into it so that :

React.render(React.createElement(MyTestReactView), document.getElementById('placeholderForReactView'));

could result in:

<div id="somestuff">
  <div>Other stuff not to delete</div>
  <div id="reactViewContent">Rendered By React</div>
</div>

instead of:

<div id="somestuff">
  <div>Other stuff not to delete</div>
  <div id="placeholderForReactView">
    <div id="reactViewContent">Rendered By React</div>
  </div>
</div>

Without recurring at Jquery is there a correct way to do it?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You don't need jQuery to work around this issue.

You just need to render into a temporary DIV and extract the content and replace the existing element. I've added the id="destination" so that the element can be easily retrieved from the temporary element.

var Hello = React.createClass({
    render: function() {
        return <div id="destination">Hello {this.props.name}</div>;
    }
});

// temporary render target
var temp = document.createElement("div");
// render
React.render(<Hello name="World" />, temp);
// grab the container
var container = document.getElementById("container");
// and replace the child
container.replaceChild(temp.querySelector("#destination"), document.getElementById("destination"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...