鍍金池/ 問答/HTML/ 有關(guān)于React中主動調(diào)用file input元素的click方法時所遇到的問題

有關(guān)于React中主動調(diào)用file input元素的click方法時所遇到的問題

我自己寫了一個文件選擇組件,此組件中包涵一個原生Input file元素,它是被隱藏的,當(dāng)點擊我的容器元素的時候,通過refs拿到這個file input元素,調(diào)用該元素的click()方法直接就調(diào)出文件選擇對話框,這是沒有問題的。但是當(dāng)后來,我想在此組件暴露出一個props接口,這個props接受一個布爾類型值,名字叫做fileSelectTrigger,也就是說當(dāng)fileSelectTriggerz這個props接收到一個true時,我會在組件的componentDidUpdate這個鉤子里面調(diào)用通過refs拿到的file input元素的click方法,但是文件選擇對話框并沒有彈出來,我不能理解這是為什么。
ps: 我還嘗試了另外一些鉤子,例如componentWillUpdate、shouldComponentUpdate、componentWillReceiveProps ,我在這些鉤子中判斷fileSelectTrigger為true時,調(diào)用file input的click方法也都不能彈出文件選擇框,嘗試了異步調(diào)用還是不行。。

我沒有直接把我原來的代碼放到這里,因為代碼太多了,我直接寫了另一個例子,來描述這個問題,請看:

// FileInput.js
import { Component } from 'react'
export default class extends Component {
    componentWillReceiveProps(props){
           if(props.fileSelectTrigger == true){
               this.fileInput.click()
           }
    }
    handleClick = (event) => {
        console.log('我被點擊了!')
    }
    render() {
        return (
            <div className={'container'} >
                <Input type="file" onClick={this.handleClick} ref={el => this.fileInput = el} />
            </div>
        )
    }
}

// xxx.js
import { Component } from 'react'
import FileInput from './FileInput'
class Demo extends Component {
    state = {
        fileSelect: false
    }
    componentDidMount() {
        setTimeout(() => {
            this.setState({
                fileSelect: true
            })
        }, 2000)
    }
    render() {
        return (
            <FileInput fileSelectTrigger={this.state.fileSelect} />
        )
    }
}

// 偽代碼:將Demo掛載到#root元素

類似這樣, 當(dāng)Demo組件被掛載到#root元素,2秒后,將會setState改變狀態(tài),這時會重新render,子元素在接收到新的props時,“我被點擊了!”會輸出出來,但是文件選擇框并沒有彈出來,這是為什么,求高人解惑!!

回答
編輯回答
枕邊人

我試了focus是有效的,問題應(yīng)該是瀏覽器做了安全限制
This is due to a security restriction.Most browsers prevent submitting files when the input field didn't receive a direct click or keyboard click event as a security precaution.

2017年1月9日 05:08