javascript 反应JS。将元素附加到 DOM

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49809392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:46:29  来源:igfitidea点击:

React JS. Append element to the DOM

javascriptreactjsdomcreateelement

提问by firmfiasco

I'm new to react and I've been playing around with it the past few days. I'm trying to append a value to the DOM, I found a way to do it but I'm looking for a way to do with by

我是新来的,过去几天我一直在玩它。我正在尝试向 DOM 附加一个值,我找到了一种方法,但我正在寻找一种方法

var para = document.createElement("li");
var t = document.createTextNode(value);
para.appendChild(t);
document.getElementById("root").appendChild(para); 

But, I'm looking for a different way. I tried a few different ways but I'm stuck. Is there a way other than this way above ^^^^

但是,我正在寻找不同的方式。我尝试了几种不同的方法,但我被卡住了。除了上面的这个方法还有别的方法吗^^^^

import React, { Component } from 'react';
import { render } from 'react-dom';


export class Parent extends React.Component {
  constructor(props) {
    this.greet = this.greet.bind(this);
    this.state = { text: " " };
  }

  greet(value) {
    //console.log(value);

    var para = document.createElement("li");
    var t = document.createTextNode(value);
    para.appendChild(t);
    document.getElementById("root").appendChild(para); 

  }

  render() {
    return (
      <div>
        <Child onGreet={this.greet} />
      </div>
    )
  }
};


export class Child extends React.Component {

  constructor(props) {
    this.state = { value: '' };
    this.handleChange = this.handleChange.bind(this);
    this.eventClick = this.eventClick.bind(this);
  }

  handleChange(event) {
    this.setState({ value: event.target.value });
  }

  eventClick() {
    this.props.onGreet(this.state.value);
  }

  render() {
    return (
      <div>
<input type="text" value={this.state.value} onChange={this.handleChange} />
<button type="button" onClick={this.eventClick}>Submit </button>
      </div>
    )
  }
};

回答by justelouise

You can try to utilize React's state property.

你可以尝试利用 React 的 state 属性。

import React, { Component } from 'react';
import { render } from 'react-dom';

export class Parent extends React.Component {
  constructor(props) {
    this.greet = this.greet.bind(this);
    this.state = {
      text: [],
    };
  }

  greet(value) {
    //console.log(value);

    const {text} = this.state
    return this.setState({
      text: text.concat(value),
    });

  }

  render() {
    return (
      <div>
        <Child onGreet={this.greet} />
        <ul>
        {this.state.text.map(x => (<li>{x}</li>))}
        </ul>
      </div>
    )
  }
};

With this, the list gets populated as the value of this.state.textchanges.

有了这个,列表会随着this.state.text的值变化而填充。