【问题标题】:How to update input value using ref in ReactJS如何在 ReactJS 中使用 ref 更新输入值
【发布时间】:2021-01-08 07:41:17
【问题描述】:

我有一个输入,我只想使用 ref 更新(不使用 setState)。 构造函数(道具){ 超级(道具);

    this.Increase = this.Increase.bind(this)
    this.textInput = React.createRef();
    this.state = {
        inputVal: -1
    };
}

<div>
<input type="number" ref={textInput} placeholder="count"/>
<span onClick={this.Increase}>Increase
</span>
</div>

我有一个函数可以用来增加输入值

Increase(event){
//access ref here and update input value using ref
}

任何帮助将不胜感激。

谢谢

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    这就像改变一个普通的字段值。 你可以这样做:

    Increase(event) {
        event.preventDefault();
        this.textInput.current.value += 1;
    }
    

    【讨论】:

    • 我想使用 ref
    • 您实际上正在使用 ref (您创建的那个)。还是你说的是钩子??
    【解决方案2】:

    解决此问题的第一步是正确传递 ref:

    <div>
        <input type="number" ref={this.textInput} placeholder="count"/>
        <span onClick={this.Increase}>Increase</span>
    </div>
    

    那么你应该添加这个Increase函数:

    Increase(event) {
        event.preventDefault();
        this.textInput.current.value = "2" //everything you want;
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 2020-03-06
    • 2021-09-28
    • 1970-01-01
    • 2019-11-13
    • 1970-01-01
    相关资源
    最近更新 更多