繁体   English   中英

React js Dom元素

[英]React js Dom elements

我是React JS的新手,对DOM元素有一个问题。 我的组件中有一张桌子。 在鼠标悬停时,我要突出显示相应的单元格和行。 我想要该元素的坐标。 例如,在第4行的第3个单元格上悬停时,我希望得到的结果为{ r-4, c-3 } 我不想使用jquery查找行的位置。 我怎样才能达到那个结果?

您可以在componentDidMount添加js本机代码,并将e.target.cellIndex用于td ,将e.target.rowIndex用于row

const tds = window.document.getElementsByTagName("td");
for(var i = 0; i<= tds.length -1;i++){
    tds[i].addEventListener("mouseup", e => {
    console.log(`cell ${e.target.cellIndex +1}` , `Row : ${e.target.parentElement.rowIndex + 1}`);
  })
}

在Codepen上进行反应的现场演示: https ://codepen.io/anon/pen/oJdjJW ? editors = 1010

希望我能帮助你

您不应该自己接触DOM,那样会扼杀反应的目的

相反,您的事件侦听器应在您的组件中表示,然后react将处​​理它们

在内部,这意味着react会在必要时调用addEventListener和removeEventListener以及其他有用的优化方法

首先,您的数据应构造为嵌套数组,然后在行和单元格上进行映射

多亏了Array.prototype.map的强大功能,您才能访问行和单元格的索引

rows.map((row, rowIndex) => (
    <div>
      {row.map((cell, cellIndex) => (
        <div
          onClick={() => {
            console.log(`you clicked on ${rowIndex}, ${cellIndex}`)
          }}
        >
          {cell}
        </div>
      ))}
    </div>
  ))

这是codesandbox https://codesandbox.io/s/6zw42m4pxw中的工作示例

您可以结合使用onMouseOversetState和动态样式来实现:

 class App extends React.Component { constructor(props) { super(props); this.state = { x: null, y: null } } render() { return ( <div> <p>User is hovering over ({this.state.x}, {this.state.y})</p> <table> {(new Array(10)).fill().map((_, y) => ( <tr> {(new Array(10).fill().map((_, x) => ( <td onMouseEnter={() => this.setState({x,y})} style={{backgroundColor: (this.state.x==x || this.state.y==y) ? 'red' : 'grey'}} ></td> )))} </tr> ))} </table> </div> ) } } ReactDOM.render((<App/>), document.querySelector('#root')); 
 table { border-collapse: 'collapse' } td { padding: 1em } 
 <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> 

实际上,react无法与DOM一起使用,而是呈现DOM本身,因此jquery不能为您提供帮助,如果您想这样做,我建议您搜索有关react Refs的更多信息,可以使用ref和onclicks进行处理,希望对您有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM