如何获取引用数组

How to get a ref array

大家好!

export default class Test extends React.Component {
    constructor(props) {
        super(props);
        this.ref = [];
    }

    handleClick = () => {
        let doc;
        doc = this.refs["link" + 0];
        console.log("ref is => " + doc.innerHTML);
    }

    render() {
        return (
            <div>
                <p ref={"link" + 0} onClick={this.handleClick}> p1</p>
                <p ref={"link" + 1} onClick={this.handleClick}> p2</p>
            </div>
        );
    }
}

当我输入函数 handleClick 时,如何知道我点击了哪个 link? 感谢您的帮助!

  export default class Test extends React.Component {

    handleClick = (linkRef) => {
        console.log("ref is => " + this.refs[linkRef].innerHTML);
    }

    render() {
        return (
            <div>
                <p ref='linkOne' onClick={() => this.handleClick('linkOne')}> p1</p>
                <p ref='linkTwo' onClick={() => this.handleClick('linkTwo')}> p2</p>
            </div>
        );
    }
}

这可能对您有用

class App extends React.Component {
  constructor() {
    super();
    this.domRefs = []
  }
  handleClick() {
    console.log(this.domRefs);
  }
  render() {
    return <>
      <div onClick={this.handleClick.bind(this)} >
        <ul>
          <li ref={r => this.domRefs.push(r)} >1</li>
          <li ref={r => this.domRefs.push(r)} >2</li>
          <li ref={r => this.domRefs.push(r)} >3</li>
          <li ref={r => this.domRefs.push(r)} >4</li>
          <li ref={r => this.domRefs.push(r)} >5</li>
        </ul>
      </div>
    </>
  }
}