简体   繁体   中英

React input defaultValue focus and select

I have a component with an input-element, i use defaultValue to set the initial value. I want to focus that element and select the whole value initially, but it seems that the defaultvalue is not set when componentDidMount is called.

Do you have any tips?

i use window.setTimeout but i want to avoid that in my react-components:

        public componentDidMount(): void {
        if (this.props.focus) {
            let tInput: HTMLInputElement = ReactDOM.findDOMNode(this).getElementsByTagName("input").item(0);
            if (tInput) {
                tInput.focus();
                // FixMe: defaultValue is set too late by react so i cant set selection instantly
                if (this.props.defaultValue) {
                    window.setTimeout(
                        () => {tInput.setSelectionRange(0, this.props.defaultValue.length); },
                        100
                    );
                }
            }
        }
    }

Works fine for me:

class MyComponent extends React.Component {

    componentDidMount () {
        const { myInput } = this.refs
        myInput.focus()
        myInput.select()
    }

    render () {
        return (
            <input type='text' defaultValue='Foobar' ref='myInput' />
        )
    }
}

I wouldn't use any reactDOM methods other than render/renderToString. These apis are "escape hatches" and usage is not recommended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM