简体   繁体   English

如何在React React组件中插入DOM值?

[英]How to insert a DOM value in a react React component?

I have a HTML page, and I am inserting inside as a component a Reactjs. 我有一个HTML页面,并且正在将Reactjs作为组件插入其中。 I am reading the DOM with JavaScript vanilla and I want to insert it on this new react script. 我正在阅读具有JavaScript vanilla的DOM,并且希望将其插入此新的react脚本中。

<HTML>
<div id="element">the value I want</div>
<div id="root"></div>
</HTML>

The div id "root" is where the react was inserted I want to play with the "value" from the DOM, but inside of React div id“ root”是我要与DOM中的“ value”一起播放的React插入的位置,但是在React中

Can I do it? 我可以做吗? How 怎么样

Looks like you can add it to componentWillMount before the initial render. 看起来您可以在初始渲染之前将其添加到componentWillMount

HTML 的HTML

<div id="element">the value I want</div>
<div id="root"></div>

JSX JSX

class Test extends React.Component {

  componentWillMount() {
    const { element } = this.props;
    this.text = document.getElementById(element).textContent;
  }

  render() {
    return <div>{this.text}</div>;
  }
}

ReactDOM.render(
  <Test element="element" />,
  document.getElementById('root')
);

DEMO 演示

If you pass it as a prop, your component won't rely on the structure of the DOM, making it a little bit more reusable and testable: 如果将其作为道具传递,则您的组件将不会依赖DOM的结构,从而使其更具可重用性和可测试性:

const value = document.getElementById('element').value;

ReactDOM.render(
  <App value={value}>,
  document.getElementById('root')
);

or as Juan Mendes mentioned, pass in the elementId as a prop. 或正如胡安·门德斯(Juan Mendes)所述,将elementId传递为道具。

All you need is this 您需要的就是这个

<div ref={(ref) => { this.myDiv = ref; }}  />

And then you can get what ever you want from it with. 然后,您可以从中获得想要的一切。

this.myDiv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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