gpt4 book ai didi

reactjs - 滚动 React 时更改样式

转载 作者:行者123 更新时间:2023-12-05 03:03:34 28 4
gpt4 key购买 nike

我想添加滚动效果。开始时,元素具有 opacity: 0.2 属性。当元素到达浏览器窗口时,将属性替换为opacity: 1。此时,当我滚动时,所有元素都将属性更改为 opacity: 1。如何在浏览器中到达元素时设置此值,其余元素具有属性 opacity: 0.2

class QuestionListItem extends Component {
constructor() {
super();
this.state = {
opacity: 0.2,
};
}

componentDidMount = () => {
window.addEventListener('scroll', () => {
this.setState({
opacity: 1,
});
});
};

render() {
const { question } = this.props;
const { opacity } = this.state;
return (
<div>
<li
key={question.id}
className="Test__questions-item"
style={{ opacity: `${opacity}` }}
ref={
(listener) => { this.listener = listener; }
}
>
<p>
{question.question}
</p>
<QuestionAnswerForm />
</li>
</div>
);
}
}

我想要这样的效果https://anemone.typeform.com/to/jgsLNG

最佳答案

一个合适的解决方案可能是这样的。当然,这只是一个概念。您可以使用 getBoundingClientRect 中的 Prop 微调激活/停用逻辑。除了 top(例如高度、底部等)。重要的是,您不应在每个滚动事件上都设置组件的状态。

const activeFromPx = 20;
const activeToPx = 100;

class ScrollItem extends React.Component {
state = {
isActive: false
}

componentDidMount = () => {
window.addEventListener('scroll', this.handleScroll);
this.handleScroll();
};

handleScroll = () => {
const { top } = this.wrapRef.getBoundingClientRect();
if (top > activeFromPx && top < activeToPx && !this.state.isActive) {
this.setState({ isActive: true });
}
if ((top <= activeFromPx || top >= activeToPx) && this.state.isActive) {
this.setState({ isActive: false });
}
}

setWrapRef = ref => {
this.wrapRef = ref;
}

render() {
const { isActive } = this.state;
return (
<div
className={`scroll-item ${isActive && 'scroll-item--active'}`}
ref={this.setWrapRef}
>
{this.props.children}
</div>
)
}
}


class ScrollExample extends React.Component {
render() {
return (
<div className="scroll-wrap">
<ScrollItem>foo</ScrollItem>
<ScrollItem>bar</ScrollItem>
<ScrollItem>eh</ScrollItem>
</div>);
}
}

ReactDOM.render(<ScrollExample />, document.getElementById('root'))
.scroll-wrap {
height: 300vh;
background: lightgray;
padding-top: 55px;
}

.scroll-item {
height: 60vh;
background: lightcyan;
margin: 10px;
opacity: 0.2;
}

.scroll-item--active {
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

关于reactjs - 滚动 React 时更改样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53744690/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com