单击时添加新组件(按钮)

时间:2017-10-28 22:23:00

标签: javascript reactjs

这是一款TODO应用。 当我点击一个按钮时 - 它会询问文本并将其放在按钮标签中,并且必须创建一个空按钮,单击时会询问文本并创建另一个按钮等。

出现两个按钮,但是当我单击其中一个并输入文本时 - 会出现文本,但不会创建新按钮。请帮忙

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

class TaskButton extends Component {
constructor(props) {
    super(props);
    this.state = {
        taskName: "Undefined"
    };
}

addTask = () => {
        var taskText = prompt('What to write ?', "");
        TASKS.push()
        this.setState({
            taskName: taskText
        })
};

render() {
    return (
        <button onClick={this.addTask}>
         {this.state.taskName}
        </button>
      );
    }
  };


var test = [
<div> <TaskButton> </TaskButton> </div>, 
<div> <TaskButton> </TaskButton> </div>
];

var listItems = test.map((test, index) =>
<li key={index}>{test}</li>
);
class TaskMenu extends Component {
    render() {
        return (
            <ul>
                {listItems}
            </ul>
        )    
    }
}

ReactDOM.render(
    <TaskMenu />,
    document.getElementById("root")
);

export default TaskMenu;

1 个答案:

答案 0 :(得分:0)

使用以下代码

&#13;
&#13;
class TaskMenu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tasks: ["undefined"]
    };
    this.addTask = this.addTask.bind(this);
  }
  addTask(e){
    var task = prompt('What to write ?', "");
    var index = e.target.getAttribute("data-index");
    this.state.tasks[index] = task;
    this.setState({tasks: +index=== this.state.tasks.length-1 ? [...this.state.tasks, "undefined"]: [...this.state.tasks]});
  };
  render() {
    return (
      <ul>
        {this.state.tasks.map((task, i)=><li key={i}> <button onClick={this.addTask} data-index={i}>{task}</button> </li>)}
      </ul>
    )
  }
}


ReactDOM.render(
    <TaskMenu />,
    document.getElementById("root")
);
&#13;
<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>
<html>
<body>
<div id ="root"></div>
</body>
</html>
&#13;
&#13;
&#13;