我有一个反应组件,其中包含内联块div 项目,每个项目都有一个边框权限来提供"分隔符"视觉效果。但是,如果它达到父组件的最大宽度,无论是通过初始加载还是进一步调整窗口大小,该行的最后一项都不应具有边框权限。它应该看起来像这样:
项目 1 |项目 2 |项目 3 |项目4
项目 5 |项目 6 |项目7
我已经阅读过有关使用 jquery 来检测项目何时具有 offsetTop 值更改的信息,但我不确定它将如何与反应组件交互。任何指导都值得赞赏。
好吧,这里的诀窍是使用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"));
.container {
position: relative;
}
.item {
display: inline-block;
padding: 0 5px;
border-left: solid 2px red;
}
.item.leftmost {
border-left-color: transparent;
}
<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>
你可以使用 css:
:nth-last-child {
border-right-style: none;
}