如何保持光标在反应输入元素中的位置

时间:2019-02-18 10:49:53

标签: javascript reactjs ecmascript-6

光标一直移到末尾。从字符串中间进行编辑时如何保持光标位置?

enter image description here

我正在使用的代码是:

const rootElement = document.getElementById('root');

class MyFancyForm extends React.Component {

    constructor(props) {
        super(props);
        this.state = {myValue: ""};
    }

    handleCommaSeparatedChange = event => {
        const {value} = event.target;
        this.setState({myValue: value});
    };




    render() {
        return(
            <form >

                <div>
                    <label>
                        Cursor position looser
                        <br />
                        <input onChange={this.handleCommaSeparatedChange} value={this.state.myValue} />
                    </label>
                </div>


            </form>
        )
    }
}

const element = <MyFancyForm />;

ReactDOM.render(element, rootElement);

任何想法我该如何实现?

1 个答案:

答案 0 :(得分:0)

只需将value更改为defaultValue-对我来说在codepen和codesandbox中都可以使用

class MyFancyForm extends React.Component {

    constructor(props) {
        super(props);
        this.state = {myValue: ""};
    }

    handleCommaSeparatedChange = event => {
        const {value} = event.target;
        this.setState({myValue: value});
    };




    render() {
        return(
            <form >

                <div>
                    <label>
                        Cursor position looser
                        <br />
                        <input onChange={this.handleCommaSeparatedChange} defaultValue={this.state.myValue} />
                    </label>
                </div>


            </form>
        )
    }
}


  ReactDOM.render(
    <MyFancyForm />,
    document.getElementById('root')
  );