在React中单击按钮时显示组件
问题描述:
我是新来的反应者.仅在单击按钮后才如何渲染组件?
I am new to react. How to render a component only after clicking a button in react?
在这种情况下,单击按钮时,我必须显示一个表,该表显示数据库中的数据.
Here in my case on clicking a button I have to display a table which displays the data from the database.
我在下面附加了我的代码供您参考,第一个组件是按钮组件,而在下面您可以找到表格的组件.
I have attached my code below for your reference, the first component is the button component and below that you can find the components for the table.
我还想知道如何在单击按钮时刷新组件而不刷新整个页面.
Also I would like to know how to refresh a component on clicking a button without refreshing the entire page.
var Button = React.createClass({
render: function () {
return (
<button type="button">Display</button>
); }
});
var EmployeeRow = React.createClass({
render: function () {
return (
<tr>
<td>{this.props.item.EmployeeID}</td>
<td>{this.props.item.FirstName}</td>
<td>{this.props.item.LastName}</td>
<td>{this.props.item.Gender}</td>
</tr>
);
}
});
var EmployeeTable = React.createClass({
getInitialState: function(){
return{
result:[]
}
},
componentWillMount: function(){
var xhr = new XMLHttpRequest();
xhr.open('get', this.props.url, true);
xhr.onload = function () {
var response = JSON.parse(xhr.responseText);
this.setState({ result: response });
}.bind(this);
xhr.send();
},
render: function(){
var rows = [];
this.state.result.forEach(function (item) {
rows.push(<EmployeeRow key={item.EmployeeID} item={item} />);
});
return (
<Button />
<table className="table">
<thead>
<tr>
<th>EmployeeID</th>
<th>FirstName</th>
<th>LastName</th>
<th>Gender</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
);
} });
ReactDOM.render(<EmployeeTable url="api/Employee/GetEmployeeList" />,
document.getElementById('grid'))
答
我已经设置了沙箱来展示如何做到这一点.
I've set up a sandbox to showcase how you can do this.
- 布尔值设置为
false
的初始化状态
- 基于此布尔值有条件地渲染组件;因此最初该组件现在将显示在DOM上
- 在执行某些操作(
onClick
)时,将setState
放在布尔值上以true
- 状态更改后,组件将重新呈现,现在将显示隐藏的组件(因为布尔值已设置为
true
)
- Initialise state with a boolean set to
false
- Render the component conditionally based on this boolean; so initially the component will now show up on the DOM
- On some action (
onClick
),setState
on the boolean totrue
- The component will re-render since the state changed and will now show the hidden component (since the boolean has been set to
true
)