如何处理循环中的引用?

IT技术 javascript reactjs
2021-04-06 18:54:03

下面是我的父组件,其中包含来自循环的多个输入。我怎样才能选择一个input重点?ref在这种情况下,我是否必须创建动态

class TestRef extends React.Component {
  ref = React.createRef();
  state = {
    data: [
      {
        name: "abc"
      },
      { name: "def" }
    ]
  };
  focusInput = () => this.ref.current.focus();
  render() {
    return (
      <div>
        {this.state.data.map(o => {
          return <Hello placeholder={o.name} ref={this.ref} />;
        })}
        <button onClick={this.focusInput}>focus input 1</button>
        <button onClick={this.focusInput}>focus input 2</button>
      </div>
    );
  }
}
4个回答

您可以使用回调引用来生成每个输入的动态引用并将其存储在数组中。现在您可以使用 ref 的索引来引用它们:

const Hello = React.forwardRef((props,  ref) => <input ref={ref} />);

class Button extends React.Component {
  onClick = () => this.props.onClick(this.props.id);

  render() {
    return (
      <button onClick={this.onClick}>{this.props.children}</button>
    );
  }
}

class TestRef extends React.Component {
  state = {
    data: [
      {
        name: "abc"
      },
      { name: "def" }
    ]
  };
  
  inputRefs = [];
  
  setRef = (ref) => {
    this.inputRefs.push(ref);
  };
  
  focusInput = (id) => this.inputRefs[id].focus();
  
  render() {
    return (
      <div>
        {this.state.data.map(({ name }) => (
          <Hello 
            placeholder={name} 
            ref={this.setRef} 
            key={name} />
        ))}
        <Button onClick={this.focusInput} id={0}>focus input 1</Button>
        <Button onClick={this.focusInput} id={1}>focus input 2</Button>
      </div>
    );
  }
}

ReactDOM.render(<TestRef />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

如果列表不是静态的,并且项目可能会被删除/替换,您可能应该使用WeakMap来保存 refs,或者任何其他通过常量添加 ref 的方法id您还应该在使用 ref 之前进行检查,因为它可能不存在:

const Hello = React.forwardRef((props,  ref) => <input ref={ref} />);

class Button extends React.Component {
  onClick = () => this.props.onClick(this.props.id);

  render() {
    return (
      <button onClick={this.onClick}>{this.props.children}</button>
    );
  }
}

class TestRef extends React.Component {
  state = {
    data: [{ name: "abc" }, { name: "def" }, { name: "ghi" }]
  };
  
  componentDidMount() {
    setTimeout(() => {
      this.setState(({ data }) => ({
        data: data.slice(0, -1)
      }))
    }, 3000);
  }
  
  inputRefs = new WeakMap;
  
  setRef = (id) => (ref) => {
    this.inputRefs.set(id, ref);
  };
  
  focusInput = (id) => {
    const input = this.inputRefs.get(id);
    
    if(input) input.focus(); // use only if the ref exists - use optional chaining ?. if possible instead
  }
  
  render() {
    const { data } = this.state;
  
    return (
      <div>
        {data.map(o => (
          <Hello 
            placeholder={o.name} 
            ref={this.setRef(o)} 
            key={o.name} />
        ))}
        
        <br />
        
        {data.map((o, i) => (
          <Button onClick={this.focusInput} id={o} key={o.name}>focus input {i + 1}</Button>
        ))}
      </div>
    );
  }
}

ReactDOM.render(<TestRef />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

如果第一个 Hello 组件被删除会发生什么?裁判仍然一致吗?例如 refs[0] 仍然指向被删除的旧 Hello 不是吗?
2021-05-29 18:54:03
这对功能性组件不起作用吗...我看到您有一个函数在加载时生成引用。我看到了 ref 参数,但我没有看到它作为参数传入?这是一个特殊的关键词还是我遗漏了什么?
2021-05-30 18:54:03
this.setRef函数<Hello>作为 ref传递给组件。<Hello>分量通过裁判的<input>,其调用函数,并传递ref通过给它(ref)阅读回调 refs
2021-05-31 18:54:03
我只是想知道 (ref) 是从哪里来的,因为没有传入任何内容......
2021-06-12 18:54:03
非常有用的解决方案
2021-06-21 18:54:03

如果您在 2020 年遇到这个问题,这里是您如何使用循环中的创建钩子创建多个引用

   const MyComponent=(){
    // empty list to put our refs in
    let LiRefs = []
    
    return (
        <React.Fragment>
          <ul className="event-list">
            // Check if my data exists first otherwise load spinner 
            {newData ? (
              newData.map((D) => {
                // the cool part inside the loop 
                // create new ref 
                // push it into array 

                const newRef = createRef();
                LiRefs.push(newRef);
                return (
                  // link it to your li 
                  // now you have list of refs that points to your list items 
                  <li key={D._id} ref={newRef}>
                    title : {D.title} <br />
                    description : {D.description}
                    <br />
                    data : {D.date} <br />
                    price : {D.price}
                    <br />
                    <div>creator : {D.creator.username}</div>
                    {authData.token && (
                      <button type="button" id={D._id} onClick={handelBooking}>
                        Book
                      </button>
                    )}
                  </li>
                );
              })
            ) : (
              <Spinner />
            )}
          </ul>
        </React.Fragment>
      );
 }
尽管通过一些重构,该模式有效且可读,但我删除了对该想法的反对票。
2021-05-23 18:54:03
我希望 2020 年的答案使用钩子而不是createRef. 这种方法有一些注意事项,尤其是当列表是动态的时。useRef应该使用而不是createRef甚至更好的回调引用。
2021-06-20 18:54:03
我没有看到 .map 有这样的副作用的很酷的部分......
2021-06-21 18:54:03

使用一般用途Focus hook

// General Focus Hook
const useFocus = (initialFocus = false, id = "") => {
    const [focus, setFocus] = useState(initialFocus)
    return ([
        (newVal=true) => setFocus(newVal), {
            autoFocus: focus,
            key: `${id}${focus}`,
            onFocus: () => setFocus(true),
            onBlur: () => setFocus(false),
        },
    ])
}

const data: [{
        name: "abc"
    },{ 
        name: "def" 
}]

const TestRef = () => {

    const focusHelper = data.map( (_,i) => {
        const [setFocus, focusProps]= useFocus(false, i)
        return {setFocus, focusProps}
    }) 

    return (
      <div>
        {data.map( (o,i) => (
          <Hello placeholder={o.name} {...focusHelper[i].focusProps} />;
        ))}
        <button onClick={() => focusHelper[0].setFocus()}>focus input 1</button>
        <button onClick={() => focusHelper[1].setFocus()}>focus input 2</button>
      </div>
    );
}

您可以在此处找到更多信息:渲染后将焦点设置在输入上

我发现了另一种解决这个问题的方法:

let dataCount = 0;

class TestRef extends React.Component {
  state = {
    data: [
      {
        name: "abc"
      },
      { name: "def" }
    ]
  };
  focusInput = (thisHello) => this[`ref${thisHello}`].current.focus();
  render() {
    return (
      <div>
        {this.state.data.map(o => {
          dataCount++
          return <Hello placeholder={o.name} ref={(el) => { this[`ref${dataCount}`] = el; }} />;
        })}
        <button onClick={() => this.focusInput(1)}>focus input 1</button>
        <button onClick={() => this.focusInput(2)}>focus input 2</button>
      </div>
    );
  }
}

dataCount,如果您的Hello元素有一个键或唯一的ID,以用作一个变量是不必要的。