我有一个反应组件,其中包含内联块div项目,每个项目都有一个右边的边框,以提供一个“分隔符”。视觉。但是,如果它达到父组件的最大宽度,无论是通过初始加载还是进一步调整窗口大小,该行的最后一项都不应该具有右边界。看起来应该是这样的:
第1项|第2项|第3项|第4项
第5项|第6项|第7项
我已经读过使用jquery来检测项目何时更改了offsetTop值,但我不确定它将如何与react组件进行交互。任何指导都表示赞赏。
答案 0 :(得分:0)
您可以使用css:
:nth-last-child {
border-right-style: none;
}
答案 1 :(得分:0)
嗯,这里的诀窍是使用ref
来获得项目的左偏移量,如果项目的左偏移量为0
,则向其添加leftmost
类。计算在安装组件后完成(在componentDidMount
方法中)。
而且,我添加version
道具,在每个窗口调整大小时增加(去抖动以避免过度更新,如果需要,可以降低超时或完全删除它)强制重新计算边界状态调整浏览器窗口大小时。
确保以完整页面模式运行演示,以查看调整浏览器窗口大小时会发生什么。
class Item extends React.Component {
constructor(props){
super(props);
this.state = {
isLeftMost: false
};
this.recalculateBorder = () => {
if(this.el){
this.setState({isLeftMost: this.el.offsetLeft === 0});
}
}
}
componentDidMount(){
this.recalculateBorder();
}
componentDidUpdate(){
this.recalculateBorder();
}
shouldComponentUpdate(nextProps, nextState){
return (nextProps.label !== this.props.label)
|| (nextProps.version !== this.props.version)
|| (nextState.isLeftMost !== this.state.isLeftMost);
}
render(){
let cl = this.state.isLeftMost ? "item leftmost" : "item";
return (
<div className={cl} ref={el => this.el = el}>{this.props.label}</div>
);
}
}
class Container extends React.Component {
constructor(props){
super(props);
this.state = { version: 0 };
let _updateDimensions = () => {
this.setState({version: this.state.version+1 });
}
this.updateDimensions = _.debounce(_updateDimensions, 25);
}
componentDidMount() {
window.addEventListener("resize", this.updateDimensions);
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions);
}
render(){
let items = [];
for(let i = 0; i<30; i++){
items.push(<Item key={i} label={"item " + i} version={this.state.version} />);
}
return (
<div className="container">
{items}
</div>
);
}
}
ReactDOM.render(<Container />, document.getElementById("root"));
&#13;
.container {
position: relative;
}
.item {
display: inline-block;
padding: 0 5px;
border-left: solid 2px red;
}
.item.leftmost {
border-left-color: transparent;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<div id="root"></div>
&#13;