React createRef循环动态赋值ref

 react的refs已经是过时的API了,不适合用于循环动态赋值ref,最近又在项目中遇到需要循环动态赋值ref,这是用createRef的方法,在此记录一下,亲测有效!

handleChange = (key) => {
    this[`input${key}Ref`] = React.createRef();
}

handleSave = () => {
    const { list } = this.state;
    for (let item of list) {
        if (item.value && item.value.length > 100) {
          Toast.show(`${item.name}不能超过100个字符`);
          this[`input${item.key}Ref`].current&&this[`input${item.key}Ref`].current.focus();
          return;
        }
    }
    // 写接口等其他逻辑
 }

render() {
    const { list } = this.state;
    <div>
        {
            list.map(item=>{
              <Input
                  ref={this[`input${item.key}Ref`]}
                  value={item.value}
                  onChange={() => { this.handleChange(item.key) }}
              />
            })
        }
        <Button type="primary" onClick={this.handleSave}>保存</Button>
     </div>
}


版权声明:本文为weixin_47292253原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。