【问题标题】:Set focus on dynamically generated components using refs使用 refs 将焦点放在动态生成的组件上
【发布时间】:2018-12-21 03:39:26
【问题描述】:

我必须创建一些动态引用,以便将焦点集中在自定义组件中包含的 Input

目前这是我渲染元素的方式:

const countRow = denom => {
  this[`${denom.id}-ref`] = React.createRef();
  return (
    <CountRow
    ref={this[`${denom.id}-ref`]}
    id={`${denom.name.singular.toLowerCase()}-${denom.id}`}
    tenderValue={denom.value}
    label={denom.denomination.label}
    onChange={(e, value) => this.handleBillsOnChange(e, denom)}
    onEnter={() => this.onEnter(denom)}
  />
}

{itterableArray.map(item => countRow(item)}

在我的onEnterFunction 中,我试图从一个&lt;CountRow /&gt; 移动到下一个。

在函数结束时:

onEnter = denom => {
  //some stuff that doesn't matter
  this[`${denom.id}-ref`].focus()
}

onEnter 函数的最后一行总是在爆炸。说:
TypeError: _this["".concat(...)].focus is not a function

有人可以为我需要做什么来选择特定&lt;CountRow /&gt; 的焦点提供指导吗?

【问题讨论】:

  • 您似乎错过了结束反引号。
  • 抱歉,这只是 SO 错误,代码中没有丢失。问题已编辑
  • 使用_this["".concat(...)].current.focus,因为CountRow是一个自定义类组件而不是一个HTML元素,CountRow应该暴露一个focus函数属性。见reactjs.org/docs/refs-and-the-dom.html

标签: javascript reactjs react-ref


【解决方案1】:

例子

const countRow = denom => {
    let ref=React.createRef();
    let onEnter = () => {
        ref.current.focus();
    }
    //setTimeout(onEnter,3000)
    return (
        <CountRow
            ref={ref}
            //   id={`${denom.name.singular.toLowerCase()}-${denom.id}`}
            //   tenderValue={denom.value}
            //   label={denom.denomination.label}
            //   onChange={(e, value) => this.handleBillsOnChange(e, denom)}
            onEnter={onEnter}
        />)
};

class CountRow extends React.Component {
    constructor(props) {
        super(props);
        this.myRef=React.createRef();
        this.focus=()=>this.myRef.current.focus(); 
    }
    render() {
        return <input type="text" ref={this.myRef}/>
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 2010-12-11
    • 2022-01-01
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    相关资源
    最近更新 更多