2016-10-24 32 views
2

我在探索Cx,一個基於Reacthttp://cx.codaxy.com/)的有趣的新框架,我無法弄清楚如何訪問組件內的DOM元素。Cx框架:如何訪問Cx中的DOM元素?

基本上,我有一個簡單的小部件,其中包含一些文本和一個按鈕,並在按鈕單擊我想要將該文本複製到剪貼板,並且由於瀏覽器的安全限制,這必須通過選擇文本輸入欄內部,執行document.execCommand('copy'); 在反應過來,我會用ref,它會是這個樣子:

class MyWidget extends React.Component {  
    copyToClipboard =() => { 
     // copy text from this.textInput to clipboard... 
     // select text 
     this.textInput.select(); 
     try { 
      // copy selected text 
      document.execCommand('copy'); 
      this.textInput.blur(); // deselect text 
     } catch (err) { 
      alert('Please press CTRL/CMD+C to copy'); 
     } 
    } 
    render(){ 
     return (
      <div> 
       <span className="inputWithButton"> 
       <input 
        ref={(input) => this.textInput = input} 
        type="text" value="some text..." 
        onClick={this.copyToClipboard} 
       /> 
       <button onClick={this.copyToClipboard} > 
        Copy to clipboard 
       </button> 
       </span> 
      </div> 
     ); 
    } 
} 

但CX並不在它的自定義組件使用refs。有沒有其他方法可以實現這一目標?

任何幫助將不勝感激。

回答

1

當CX部件需要訪問DOM它通常在這兩種方式中的一種進行處理:

  1. 使用event.target

copyToClipboard回調方法,第一個參數是事件。 event.target指向被點擊的DOM元素。你可以使用event.target.previousSibling來獲得輸入,儘管如果你改變了你的DOM結構,這會讓你覺得不舒服,並且會崩潰。

  • 使用陣營部件
  • 這是完全細返回反應,從CX部件渲染方法。所以你可以使用你已經寫過的東西,只是包裝在Cx部件中。

    render(context, instance, key) { 
        return <MyWidget key={key} ... /> 
    } 
    
    +0

    解決了!謝謝! –