在React中显示或隐藏元素 [英] Show or hide element in React
问题描述
我第一次搞乱React.js,找不到通过点击事件在页面上显示或隐藏某些内容的方法。我没有加载任何其他库到页面,所以我正在寻找一些使用React库的本地方式。这就是我到目前为止所拥有的。我想在点击事件触发时显示结果div。
I am messing around with React.js for the first time and cannot find a way to show or hide something on a page via click event. I am not loading any other library to the page, so I am looking for some native way using the React library. This is what I have so far. I would like to show the results div when the click event fires.
var Search= React.createClass({
handleClick: function (event) {
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
方法:
The key is to update the state of the component in the click handler using setState
. When the state changes get applied, the render
method gets called again with the new state:
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>
);
}
});
ReactDOM.render(<Search />, document.getElementById('container'));
http: //jsfiddle.net/kb3gN/15084/
这篇关于在React中显示或隐藏元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!