简体   繁体   中英

ClipboardJS with React, using document.getElementById()

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

I adjusted your code and created a simple integration of clipboard.js with React.

Here's the fiddle: https://jsfiddle.net/mrlew/ehrbvkc1/13/ . Check it out.

Your code is fine you just have a few issues:

  • you are binding clipboard.on in componentDidUpdate which won't trigger here since you are not really changing anything (in the ClipboardField component) that triggers this event.
  • You are passing {this.someCode} in the code prop which would be undefined should just be {someCode}

So it's just a matter of moving your clipboard.on to the componentDidMount right after the new Clipboard and use code={someCode}

https://jsfiddle.net/yy8cybLq/

--

In React whenever you want to access the actual dom element of your component we use what react calls as refs, I would suggest you do this rather than using getElementById as this is the "best practice".

However stateless components (like your ClipboardField component above) can't have refs so you just need to change it to be a normal component.

Here's a fiddle with your code but using refs instead: https://jsfiddle.net/e5wqk2a2/

I tried including links to the react docs for stateless components and refs but apparently don't have enough "rep" to post more than 2 links, anyways quick google search should point you in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM