React:如果输入值按状态改变,则触发onChange? [英] React: trigger onChange if input value is changing by state?

查看:926
本文介绍了React:如果输入值按状态改变,则触发onChange?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我不想只在点击按钮时才调用handleChange。它与handleClick无关。我在@shubhakhatri回答的评论中给出了一个例子。

I don't want to call handleChange only if the button has been clicked. It has nothing to do with handleClick. I gave an example in the @shubhakhatri answer's comment.

我想根据状态改变输入值,值正在改变但是它不会触发 handleChange()方法。如何触发 handleChange()方法?

I want to change the input value according to state, the value is changing but it doesn't trigger handleChange() method. How can I trigger handleChange() method ?

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    value: 'random text'
    }
  }
  handleChange (e) {
    console.log('handle change called')
  }
  handleClick () {
    this.setState({value: 'another random text'})
  }
  render () {
    return (
      <div>
        <input value={this.state.value} onChange={this.handleChange}/>
        <button onClick={this.handleClick.bind(this)}>Change Input</button>
      </div>
    )
  }
}

ReactDOM.render(<App />,  document.getElementById('app'))

这是codepen链接: http://codepen.io/madhurgarg71/pen/qrbLjp

Here is the codepen link: http://codepen.io/madhurgarg71/pen/qrbLjp

推荐答案

你需要触发 onChange 事件。在文本输入onChange侦听输入事件。

You need to trigger the onChange event manually. On text inputs onChange listens for input events.

所以在你 handleClick 你需要触发事件的函数,如

So in you handleClick function you need to trigger event like

handleClick () {
    this.setState({value: 'another random text'})
    var event = new Event('input', { bubbles: true });
    this.myinput.dispatchEvent(event);
  }

完整代码

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    value: 'random text'
    }
  }
  handleChange (e) {
    console.log('handle change called')
  }
  handleClick () {
    this.setState({value: 'another random text'})
    var event = new Event('input', { bubbles: true });
    this.myinput.dispatchEvent(event);
  }
  render () {
    return (
      <div>
        <input readOnly value={this.state.value} onChange={(e) => {this.handleChange(e)}} ref={(input)=> this.myinput = input}/>
        <button onClick={this.handleClick.bind(this)}>Change Input</button>
      </div>
    )
  }
}

ReactDOM.render(<App />,  document.getElementById('app'))

Codepen

Codepen

编辑:
正如@Samuel在评论中建议的那样,如果你<$ c,更简单的方法是从 handleClick 调用 handleChange $ c>在 handleChange 中不需要事件对象
喜欢

As Suggested by @Samuel in the comments, a simpler way would be to call handleChange from handleClick if you don't need to the event object in handleChange like

handleClick () {
    this.setState({value: 'another random text'})
    this.handleChange();
  }

我希望这是你需要的,它可以帮助你。

I hope this is what you need and it helps you.

这篇关于React:如果输入值按状态改变,则触发onChange?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆