简体   繁体   中英

Passing data into a React component from the HTML page?

I have a React app like this:

index.html:

<div class="asset_infos" data-keyID="msg_1"></div>
<div class="asset_infos" data-keyID="msg_2"></div>
...
<div class="asset_infos" data-keyID="msg_n"></div>

and index.js:

var Msg = props => (
    <div>It is { props.keyID }</div>
);

document.querySelectorAll('.asset_infos')
  .forEach(domContainer => {
    ReactDOM.render(<Msg {...(domContainer.dataset)} />,
      domContainer
    );
  });

I want the data from the data-keyID attribute of each < div > to be transferred to the Msg variable and to be diplayedd, but it doesn't. Do you know how to do so?

You can pass the props like below. See the demo https://jsfiddle.net/uveh5d48/1/

document.querySelectorAll('.asset_infos')
.forEach(domContainer => {
   ReactDOM.render(<Msg keyID = {domContainer.dataset.keyid} />,
     domContainer
   );
});

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