Jak mogę przekonać Reacta do ponownego renderowania widoku po zmianie rozmiaru okna przeglądarki?
tło
Mam kilka bloków, które chcę układać indywidualnie na stronie, ale chcę też, aby były aktualizowane po zmianie okna przeglądarki. Końcowym rezultatem będzie coś w stylu Bena Holland'a na Pinterest, ale napisane przy użyciu React nie tylko jQuery. Nadal jestem daleko.
Kod
Oto moja aplikacja:
var MyApp = React.createClass({
//does the http get from the server
loadBlocksFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
mimeType: 'textPlain',
success: function(data) {
this.setState({data: data.events});
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
componentWillMount: function() {
this.loadBlocksFromServer();
},
render: function() {
return (
<div>
<Blocks data={this.state.data}/>
</div>
);
}
});
React.renderComponent(
<MyApp url="url_here"/>,
document.getElementById('view')
)
Następnie mam Blockkomponent (odpowiednik Pinw powyższym przykładzie Pinterest):
var Block = React.createClass({
render: function() {
return (
<div class="dp-block" style={{left: this.props.top, top: this.props.left}}>
<h2>{this.props.title}</h2>
<p>{this.props.children}</p>
</div>
);
}
});
oraz lista / kolekcja Blocks:
var Blocks = React.createClass({
render: function() {
//I've temporarily got code that assigns a random position
//See inside the function below...
var blockNodes = this.props.data.map(function (block) {
//temporary random position
var topOffset = Math.random() * $(window).width() + 'px';
var leftOffset = Math.random() * $(window).height() + 'px';
return <Block order={block.id} title={block.summary} left={leftOffset} top={topOffset}>{block.description}</Block>;
});
return (
<div>{blockNodes}</div>
);
}
});
Pytanie
Czy powinienem dodać rozmiar okna jQuery? Jeśli tak to gdzie?
$( window ).resize(function() {
// re-render the component
});
Czy istnieje bardziej „reakcyjny” sposób na zrobienie tego?
this.updateDimensionsPrzekazaneaddEventListenerjest tylko gołe odniesienia funkcja, która nie będzie miała wartość dlathiskiedy dzwonił. Czy do dodania należy użyć funkcji anonimowej lub wywołania .bind ()this, czy też źle zrozumiałem?