【问题标题】:React js: mouse cursor always at end of input element when edit textReact js:编辑文本时鼠标光标始终位于输入元素的末尾
【发布时间】:2016-12-14 23:59:30
【问题描述】:

我在我的 React 应用程序中使用了一个输入元素。在应用程序中,我尝试使用 Flux 架构。因此,当我更改输入时,我会立即将文本同步到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

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

谢谢。

【问题讨论】:

    标签: javascript reactjs input


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-05
      • 2011-11-24
      • 1970-01-01
      • 2013-07-20
      • 1970-01-01
      • 2011-11-08
      相关资源
      最近更新 更多