【问题标题】:React input defaultValue focus and select反应输入 defaultValue 焦点并选择
【发布时间】:2016-09-28 12:54:20
【问题描述】:

我有一个带有输入元素的组件,我使用 defaultValue 来设置初始值。 我想聚焦该元素并最初选择整个值,但似乎调用 componentDidMount 时未设置默认值。

你有什么建议吗?

我使用 window.setTimeout 但我想在我的 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
                    );
                }
            }
        }
    }

【问题讨论】:

  • 你能发布渲染调用吗?你是如何设置默认值的?

标签: select reactjs input focus


【解决方案1】:

对我来说很好用:

class MyComponent extends React.Component {

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

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

我不会使用除了 render/renderToString 之外的任何 reactDOM 方法。这些 api 是“逃生舱”,不建议使用。

【讨论】:

    猜你喜欢
    • 2013-07-18
    • 1970-01-01
    • 2017-07-31
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2013-02-06
    相关资源
    最近更新 更多