ReactJS如何在由另一个渲染函数动态渲染的组件上使用Ref来聚焦元素?

时间:2020-01-08 16:01:23

标签: javascript reactjs

我有一个类组件,该组件呈现元素列表,并且在事件发生时需要将它们聚焦。

这是示例代码

class page extends React.Component {
   state = {
      items: [array of objects]
   }

   renderList = () => {
      return this.state.items.map(i => <button>{i.somekey}</button>)
   }

   focusElement = (someitem) => {
      //Focus some item rendered by renderList()
   }

   render(){
      return(
         <div>
            {this.renderList()}
            <button onClick={() => focusElement(thatElement)}>
         </div>
      )
   }
}

我知道我需要使用裁判,但我尝试了几种方法来做,但我无法正确设置这些裁判。

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

您应该使用要关注的每个按钮的createRef方法,还必须将此引用传递给您创建的focusElement方法:

const myList = [
  { id: 0, label: "label0" },
  { id: 1, label: "label1" },
  { id: 2, label: "label2" },
  { id: 3, label: "label3" },
  { id: 4, label: "label4" },
  { id: 5, label: "label5" }
];

export default class App extends React.Component {
  state = {
    items: myList,
    //This is the list of refs that will help you pick any item that ou want to focus
    myButtonsRef: myList.map(i => React.createRef(i.label))
  };

  // Here you create a ref for each button
  renderList = () => {
    return this.state.items.map(i => (
      <button key={i.id} ref={this.state.myButtonsRef[i.id]}>
        {i.label}
      </button>
    ));
  };

  //Here you pass the ref as an argument and just focus it
  focusElement = item => {
    item.current.focus();
  };

  render() {
    return (
      <div>
        {this.renderList()}
        <button
          onClick={() => {
            //Here you are able to focus any item that you want based on the ref in the state
            this.focusElement(this.state.myButtonsRef[0]);
          }}
        >
          Focus the item 0
        </button>
      </div>
    );

  }
}

如果您想使用此代码,这里是sandbox