【问题标题】:How can I prevent the browser from scrolling to top of the page when checking the checkbox?选中复选框时,如何防止浏览器滚动到页面顶部?
【发布时间】:2017-04-12 17:36:48
【问题描述】:

我知道我们可以在 stackoverflow 上找到很多类似的问题。我正在使用 ReactJS。

<body>
  <table>
    <tbody>
      <tr>
        <td>
          <input type="checkbox" id="checkbox1">
          <p>Check 1</p>
          <a></a>
        </td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" id="checkbox1">
          <p>Check 2</p>
          <a></a>
        </td>
      </tr>
    </tbody>
  </table>
</body>

这是我正在使用的示例。有超过 35 个复选框,每当我点击其中任何一个时,页面都会跳到顶部。[![在此处输入图像描述][1]][1]

正如我在带有 100 个复选框的简单 html 页面上尝试过的那样,它工作正常,但在我的 React 代码中。有跳转

这是我处理更改事件的方式:

<input type="checkbox" onChange={this.props.checkedList} name="article" value={item.id}/>

 checkedList(e) {
let id = e.target.value
if (this.state.marked.includes(id)) {
  let filteredArray = this.state.marked.filter(item => item !== id)
  this.setState({marked: filteredArray});
}
else {
  this.setState({marked: this.state.marked.concat(id)});
}
}

【问题讨论】:

  • 你是如何处理 Check 事件的?
  • 当你在事件中调用 setState 时,它​​会再次渲染组件
  • @RichaGarg 评论这些行有效,但你能告诉我应该如何跟踪检查的项目
  • 您能否分享您的整个代码。 marked 状态是父组件的状态,更改后会再次渲染它。
  • @RichaGarg 我不能发布更多代码,因为它很大,你能告诉我一些复选框值如何存储在 React js 中的例子吗?谢谢

标签: javascript html css reactjs


【解决方案1】:

当您在事件中调用 setState 时,它​​会导致呈现状态为 marked 的组件。您应该使用组件中的局部变量来处理标记的数组或处理shouldComponentUpdate。您可以找到详细信息here 使用它。

【讨论】:

    【解决方案2】:

    您也许可以使用aria-label="test"

    例子:

    <input  aria-label="test" id="test" type="checkbox" />
    

    aria-label 属性用于定义一个字符串来标记 当前元素。在文本标签不可见的情况下使用它 屏幕。 (如果有可见的文本标记元素,使用 aria-labelledby 代替。)

    参考 - https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-label_attribute

    【讨论】:

    • 我也用过 label 和 aria-label 但它没有帮助
    猜你喜欢
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-05
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多