【发布时间】:2018-08-17 11:42:22
【问题描述】:
1) 我正在尝试自动滚动到列表组中的下一项。例如,如果用户回答第一个问题,它应该自动滚动到第二个问题。 (反应)和 onSubmit 它应该滚动到第一个未回答的问题
2) 当用户在移动视图中查看此列表时,“是”或“否”单选按钮应显示在中心,并且还应显示提交和清除按钮(引导)
3)如何知道从下拉列表中选择了哪个项目并在控制台中显示。
【问题讨论】:
标签: javascript reactjs bootstrap-4
1) 我正在尝试自动滚动到列表组中的下一项。例如,如果用户回答第一个问题,它应该自动滚动到第二个问题。 (反应)和 onSubmit 它应该滚动到第一个未回答的问题
2) 当用户在移动视图中查看此列表时,“是”或“否”单选按钮应显示在中心,并且还应显示提交和清除按钮(引导)
3)如何知道从下拉列表中选择了哪个项目并在控制台中显示。
【问题讨论】:
标签: javascript reactjs bootstrap-4
有多种方法可以实现这一目标。一种方法是通过“vanilla js”添加一个滚动到表单中的项目的方法,然后在 onInputChanged 和 onSubmut 方法中使用它。
您可以在组件中将此函数定义为:
// Scrolls the list to a list item by list item index
scrollToItemByIndex = (index) => {
// Find the list item element (by index), and scroll wrapper element
const scrollItem = document.querySelector(`[scrollIndex="${ (index) }"]`)
const scrollWrapper = document.querySelector(`[scrollWrapper="scrollWrapper"]`)
if(scrollItem && scrollWrapper) {
// If list item found in DOM, get the top offset
const itemRect = scrollItem.offsetTop // [UPDATED]
const wrapperRect = scrollWrapper.offsetTop // [UPDATED]
// Scroll the wrapper to the offset of the list item we're scrolling to
scrollWrapper.scrollTo(0, itemRect - wrapperRect)
}
}
您的onInputChange 函数可以更新如下:
onInputChange = ({ target }) => {
const { cards } = this.state;
const { options } = this.state;
const nexState = cards.map((card, index) => {
if (card.cardName !== target.name) return card;
const options = card.options.map(opt => {
const checked = opt.radioName === target.value;
return {
...opt,
selected: checked
}
})
// [ADD] When input changes (ie something is set), scroll to next item
this.scrollToItemByIndex( index + 1 )
const style = options.every(option => !option.selected) ? 'danger' : 'info'
return {
...card,
style,
options
}
});
this.setState({ cards: nexState })
}
此外,您的onSubmit 将被更新以滚动到任何无效的表单项:
onSubmit = () => {
this.state.cards.forEach((card, index) => {
var invalid = card.options.every(option => !option.selected)
if (invalid) {
card.style = 'danger'
// [ADD] this item has invalid input, so scroll to it
this.scrollToItemByIndex(index)
}
else {
card.style = 'info'
}
});
...
}
最后,您需要使用以下内容更新组件的渲染方法,以确保上述查询选择器正常运行:
<ul class="nav nav-pills nav-stacked anyClass" scrollWrapper="scrollWrapper">
和:
{cards.map((card, idx) => (<ListGroup bsStyle="custom" scrollIndex={idx}>
...
</ ListGroup >)}
[更新] 可以在此处找到完整的工作示例: https://stackblitz.com/edit/react-z7nhgd?file=index.js
希望这会有所帮助!
【讨论】: