当编辑文本时,React js:鼠标光标始终位于输入元素的末尾

时间:2016-08-09 04:45:33

标签: javascript reactjs input

我在我的React app中使用了一个输入元素。在应用程序中,我尝试使用Flux架构。因此,当我更改输入时,我立即将文本同步到Store处理程序中的onChange。然后,Store会向订阅者触发一个事件,即订阅者本身从Store中提取数据。

我使用Pub-sub js来实现事件机制,这是我的代码:

var MyStore = function MyStore() {
    var _this = this;

    this.update = function (name, value) {
        _this.info[name] = value;
        PubSub.publish('STORE_UPDATE');
    };

    this.set = function (obj) {
        _this.info = obj;
    };

    this.get = function () {
        return _this.info;
    };

    this.info = null;
};

var myStore = new MyStore();

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            info: {
                width: '1230000'
            }
        }

        myStore.set({
            width: '1230000'
        })

        PubSub.subscribe('STORE_UPDATE', () => {
            this.setState({
                info: myStore.get()
            })
        })

    }
    onChange (e) {
      myStore.update('width', e.target.value);
    }
    render () {
        return (
            <div className="ui form">
                <input value={this.state.info.width} onChange={this.onChange} />
            </div>
        )
    }
}

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

这是Demo on fiddle

我想知道为什么会这样,我该如何解决这个问题。

谢谢。

1 个答案:

答案 0 :(得分:0)

我认为现在为时已晚,但这个错误与反应中的异步更新错误有关。 (仅在Chrome中发生)。 我发现的脏修复是在发送到商店之前设置组件的状态。 https://jsfiddle.net/69z2wepo/68244/

onChange (e) {
  this.setState({info: {
     width: e.target.value
  }});
  myStore.update('width', e.target.value);
}