我有一个表格,它显示为通过表单从前端对我的后端进行 API 调用的结果。问题是每行数据都会生成标题,从而产生冗余。
我研究refs
了一种访问HTML
元素的方法。
var BountyHunters = React.createClass({
state : {toggleClass: true},
getInitialState: function(){
return({
bountyHunters: []
})
},
render: function () {
var bountyHunters = this.state.bountyHunters
bountyHunters = bountyHunters.map(function(bountyHunter, index){
return (
<tbody key={index}>
<tr>
<td><span className={bountyHunter.obj.available}></span></td>
<td className="name">{bountyHunter.obj.name}</td>
<td className="rank">{bountyHunter.obj.rank}</td>
<td className="dist">{Math.floor(bountyHunter.dis / 1000)} km</td>
</tr>
</tbody>
)
})
return(
<div className="container">
<div className="sixteen columns">
<div id="bountyhunter-container">
<form id="search" onSubmit= {this.handleSubmit}>
<label>Enter your latitude</label>
<input type="text" ref="lat" placeholder="latitude" requried/>
<label>Enter your longitude</label>
<input type="text" ref="lng" placeholder="longitude" requried/>
<input type="submit" className="button-primary" value="Find Bounty Hunters"/>
</form>
<table className="u-full-width">
<thead ref="thead">
<tr>
<th>Availability</th>
<th>Name</th>
<th>Bounties Claimed</th>
<th>Distance from you</th>
</tr>
</thead>
{bountyHunters}
</table>
</div>
</div>
</div>
);
},
handleSubmit: function(e){
e.preventDefault();
var lng = this.refs.lng.value;
var lat = this.refs.lat.value;
this.refs.thead.style = 'block';
fetch('/api/bountyHunters?lng=' + lng + '&lat=' + lat)
.then(function(data){
return data.json()
}).then(json => {
this.setState({
bountyHunters: json
})
console.log(json);
});
}
});
ReactDOM.render(<BountyHunters/>, document.getElementById('bountyHunters'))
所以你可以看到我ref
在标签中创建或使用了一个属性,<thead>
然后在handleSubmit
函数中使用它
this.refs.thead.style.display = 'block';
我相信虽然这会导致thead
元素上的所有其他属性都被撕掉,并仅用display: block
属性和值替换它们。
所以我的问题是:这是你会用 refs 做这件事的方式吗?我研究了许多add/remove
专门针对 react 的类方法,因为我知道它们是一个必须解决的许多 DOM 安装生命周期问题。但是对一个人必须经历的所有箍感到有点惊讶。有人可以指导我什么是最好的/反应式的方法吗?
在此先感谢] 1
更新
我实际上发布了代码,试图隐藏然后显示thead
标签的显示属性。我描述的行为是如果thead
在方法中返回了render
。