2016-11-05 33 views
3

的的onclick我有一個浮動按鈕(材料UI)我反應過來的項目。我想打開「選擇文件」對話框,只要我點擊它。我沒有得到任何解決方案來做到這一點。我試圖做到這一點,但沒有奏效。我不想使用jquery。打開「選擇文件」對話框上的凸起按鈕材質UI

</div> 
      <input id="myInput" type="file" style="visibility:hidden" /> 
      <FloatingActionButton className="floatingButton" backgroundColor='#293C8E' onClick ="$('#myInput').click();"> 
       <ContentAdd /> 
      </FloatingActionButton> 
     </div> 

有人可以告訴我我到底需要做什麼嗎?

回答

3

基本範例(不包括如何處理選定的文件做):

<div> 
    <input id="myInput" type="file" ref={(ref) => this.upload = ref} style={{ display: 'none' }} /> 
    <FloatingActionButton 
     className="floatingButton" 
     backgroundColor='#293C8E' 
     onClick={(e) => this.upload.click() } 
     > 
     <ContentAdd /> 
    </FloatingActionButton> 
    </div> 

所以,你FloatingActionButton的onClick處理程序手動觸發隱藏文件上傳控件的click()處理程序(input type =「file」)。隱藏上傳控件的引用是通過在其上放置一個ref回調並將該引用存儲在「this.upload」中獲得的(也可以使用DOM或jQuery來完成該操作,但ref在React中是首選)

這裏是工作的jsfiddle:https://jsfiddle.net/432yz8qg/58/

1

你可以做的伎倆與<label/>標籤的幫助:

<label htmlFor='myInput'> 
    <input id="myInput" type="file" style={{visibility: 'hidden'}} /> 
    <FloatingActionButton 
    className="floatingButton" 
    backgroundColor='#293C8E' 
    > 
    <ContentAdd /> 
    </FloatingActionButton> 
</label> 
+0

使用你給上面的代碼,對話框當我點擊按鈕時沒有打開。爲什麼? – ApurvG

+0

我應該在浮動按鈕的onClick方法中包含什麼? – ApurvG

+0

你不應該在那裏設置任何事件處理程序。標籤標籤將單擊「for」時引用的輸入(或jsx'htmlFor'情況下)的屬性輸入集中。通過設置'onClick'你將覆蓋這種行爲。 –

0

不過,我覺得我的解決方案意味着使用多個CSS規則解決更作出反應的方式比傑夫解決這個問題。

我用FlatButton與道具containerElement設置爲 「標籤」:

const { FlatButton, SvgIcon, MuiThemeProvider, getMuiTheme } = MaterialUI; 
 

 
class Example extends React.Component { 
 
    render() { 
 
    const buttonStyle = { 
 
     minWidth: '56px', 
 
     width: '56px', 
 
     minHeight: '56px', 
 
     height: '56px', 
 
     borderRadius: '28px', 
 
    }; 
 
    
 
    return (
 
     <div> 
 
     <FlatButton 
 
      containerElement="label" 
 
      backgroundColor='#293C8E' 
 
      style={buttonStyle} 
 
      > 
 
      <input type="file" style={{ display: 'none' }} /> 
 
     </FlatButton> 
 
     </div> 
 
    ); 
 
    } 
 
} 
 

 
const App =() => (
 
    <MuiThemeProvider muiTheme={getMuiTheme() }> 
 
    <Example /> 
 
    </MuiThemeProvider> 
 
); 
 

 
ReactDOM.render(
 
    <App />, 
 
    document.getElementById('container') 
 
);
<script src="https://unpkg.com/[email protected]/dist/react-with-addons.js"></script> 
 
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script> 
 
<script src="https://rawgit.com/nathanmarks/3f5196f5973e3ff7807f2bab4e603a37/raw/f409f3bf5902c211b358a3ebe7b6cd366da551e8/mui-umd.js"></script> 
 
<div id="container"></div>

更多細節在這裏:https://stackoverflow.com/a/36262984/2590861