reactjs - 在 react.js 中,显示或者隐藏元素

我想在点击事件触发时显示div 。


var Search= React.createClass({
handleClick: function (e) {
 console.log(this.prop);
},
render: function() {
return <div className="date-range">
<input type="submit" value="Search" onClick={this.handleClick} />
</div>;
}
});

var Results = React.createClass({
render: function() {
return <div id="results" className="search-results">
Some Results
</div>;
}
});
React.renderComponent( <Search /> , document.body);

时间:

关键是使用setState更新单击处理程序中组件的状态,应用状态更改后,将使用新状态再次调用render方法:


var Search = React.createClass({
 getInitialState: function() {
 return { showResults: false };
 },
 onClick: function() {
 this.setState({ showResults: true });
 },
 render: function() {
 return (
 <div>
 <input type="submit" value="Search" onClick={this.onClick} />
 { this.state.showResults ? <Results /> : null }
 </div>
 );
 }
});

var Results = React.createClass({
 render: function() {
 return (
 <div id="results" className="search-results">
 Some Results
 </div>
 );
 }
});

React.renderComponent(<Search />, document.body);

http://jsfiddle.net/kb3gN/3369/


<style type="text/css">
 .hidden { display:none; }
</style>

render: function() {
 return (
 <div className={this.props.shouldHide ? 'hidden' : ''}>
 This will be hidden if you set <tt>props.shouldHide</tt> 
 to something truthy.
 </div>
 );
}

你在状态中设置布尔值(例如,'show ),然后执行以下操作:


var style = {};
if (!this.state.show) {
 style.display = 'none'
}

return <div style={style}>...</div>

...