javascript React - 在组件内动态创建列表项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46514351/
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 06:43:19  来源:igfitidea点击:

React - Dynamic creation of List item inside component

javascriptreactjs

提问by Szach

Is there any way to add dynamical lielement into my ullist ? I'd like add my liby clicking the button. Here is example code

有没有办法将动态li元素添加到我的ul列表中?我想li通过单击按钮添加我的。这是示例代码

class Component1 extends React.Component {

    constructor() {
        super();
    }

    add() {
        let ul = document.getElementById('mylist');
        let li = document.createElement('li');
        li.appendChild(document.createTextNode({some_variables});
        ul.appendChild(li);
    }
    render() {
        return (
                <a href="#" onClick={() => this.add()}>Add</a>
                <ul id="mylist">
                    /* dynamic list ITEM  */

                </ul>
        );
    }
}

ReactDOM.render(<Component1 />, document.getElementById('root'));

Of course current function add()doesn't work on React

当然当前功能add()不适用于 React

回答by Sagiv b.g

When using react we are not "touching" the DOM as we usually do with other libraries (like jQuery).
One of the best and core features of react is the virtual DOM, the Reconciliation & diffing algorithm

使用 react 时,我们不会像通常使用其他库(如 jQuery)那样“接触”DOM。
React 的最佳和核心功能之一是虚拟 DOM,即Reconciliation & diffing 算法

React builds and maintains an internal representation of the rendered UI. It includes the React elements you return from your components. This representation lets React avoid creating DOM nodes and accessing existing ones beyond necessity, as that can be slower than operations on JavaScript objects. Sometimes it is referred to as a “virtual DOM”

React 构建并维护渲染 UI 的内部表示。它包括您从组件返回的 React 元素。这种表示让 React 避免了创建 DOM 节点并在不必要的情况下访问现有节点,因为这可能比对 JavaScript 对象的操作慢。有时它被称为“虚拟 DOM”

In react you create components (functions) that renders / returns a jsx(markup).
A simple example to your scenario could be:

在反应中,您创建呈现/返回jsx(标记)的组件(函数)。
您的场景的一个简单示例可能是:

const ListItem = ({ value, onClick }) => (
  <li onClick={onClick}>{value}</li>
);

const List = ({ items, onItemClick }) => (
  <ul>
    {
      items.map((item, i) => <ListItem key={i} value={item} onClick={onItemClick} />)
    }
  </ul>
);

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: '',
      fruites: ['Apple', 'Banana', 'Orange']
    };
  }

  onClick = () => {
    const { inputValue, fruites } = this.state;
    if (inputValue) {
      const nextState = [...fruites, inputValue];
      this.setState({ fruites: nextState, inputValue: '' });
    }
  }

  onChange = (e) => this.setState({ inputValue: e.target.value });

  handleItemClick = (e) => {console.log(e.target.innerHTML)}

  render() {
    const { fruites, inputValue } = this.state;
    return (
      <div>
        <input type="text" value={inputValue} onChange={this.onChange} />
        <button onClick={this.onClick}>Add</button>
        <List items={fruites} onItemClick={this.handleItemClick} />
      </div>
    );
  }
}


ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>