0

Originally, I had it working fine.

Then I did this and now I can't get it to work

ClipboardField.js

import React from 'react';

export default (props) => {

  return(
    <div id="clip" data-clipboard-text={props.code} onClick={props.onClick}>
      <p> Copy to clipboard.</p>
    </div>
  );
}

Field.js

class DashWizardTwoCore extends Component {

  componentDidMount(){
    const btns = document.getElementById('clip');
    const clipboard = new Clipboard(btns);
  }

  componentDidUpdate() {
    clipboard.on('success', function(e) {
      console.log(e);
    });
    clipboard.on('error', function(e) {
      console.log(e);
    });
  }


  render(){

    const someCode = "const foo = 1"

    return (
      <div>
        <ClipboardField code={this.someCode} /> }
      </div>
    );
  }
}

If you take the code out of ClipboardField and into Field it works. It's mostly, how do I use document.getElementById() in my parent component to find something in my child?

Their examples:

https://github.com/zenorocha/clipboard.js/blob/master/demo/constructor-selector.html#L18

https://github.com/zenorocha/clipboard.js/blob/master/demo/constructor-node.html#L16-L17

https://github.com/zenorocha/clipboard.js/blob/master/demo/constructor-nodelist.html#L18-L19

4

2 回答 2

1

您的代码很好,您只是遇到了一些问题:

  • 您正在绑定其中不会在此处触发,因为您并没有真正更改触发此事件的任何内容(在clipboard.on组件中)。componentDidUpdateClipboardField
  • 您正在传递未定义{this.someCode}code道具应该只是{someCode}

因此,只需在and 使用后将您向右移动clipboard.on即可componentDidMountnew Clipboardcode={someCode}

https://jsfiddle.net/yy8cybLq/

--

在 React 中,每当您想访问组件的实际 dom 元素时,我们都会使用 react 调用的 refs,我建议您这样做而不是使用getElementById,因为这是“最佳实践”。

但是,无状态组件(如ClipboardField上面的组件)不能有 refs,因此您只需将其更改为普通组件即可。

这是您的代码的一个小提琴,但使用 refs 代替:https ://jsfiddle.net/e5wqk2a2/

我尝试包含指向无状态组件和参考的反应文档的链接,但显然没有足够的“代表”来发布超过 2 个链接,无论如何快速谷歌搜索应该指向正确的方向。

于 2016-06-22T05:18:40.510 回答
1

我调整了您的代码并创建了clipboard.js与 React 的简单集成。

这是小提琴:https ://jsfiddle.net/mrlew/ehrbvkc1/13/ 。一探究竟。

于 2016-06-22T05:01:46.947 回答