我想做一个待办事项应用程序,因为我是ReactJS的初学者(是的,我正在自己学习所有内容,而且还在读高中!)。因此,我想在ul后面加上一个li!
我尝试将待办事项记录到控制台,它也起作用,但是现在我想将li添加到ul
Form.js
import React, { Component } from 'react';
import '../Styles/Forms.css';
class Form extends Component {
constructor() {
super();
this.state = { todo: '' };
this.handleTodo = this.handleTodo.bind(this);
this.handleAddTodo = this.handleAddTodo.bind(this);
}
render() {
return (
<div className='center-v-h'>
<form>
<table>
<tbody>
<tr>
<td>
<input type='text' onChange={this.handleTodo} />
</td>
</tr>
<tr>
<td>
<button onClick={this.handleAddTodo} style={{ width: '100%' }}>
Add Todo
</button>
</td>
</tr>
</tbody>
</table>
</form>
<ul id='todo'></ul>
</div>
);
}
handleTodo(e) {
this.setState({ todo: e.target.value });
}
handleAddTodo(e) {
e.preventDefault();
console.log(`Todos: ${this.state.todo}`);
}
}
export default Form;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Form from './Components/Form';
function App() {
return (
<div>
<Form />
</div>
);
}
ReactDOM.render(<App />, document.querySelector('#root'));
答案 0 :(得分:4)
您具有这样的状态:
this.state = { todos:
[
{id: 1, text: "Todo 1"},
{id: 2, text: "Todo 2"},
{id: 3, text: "Todo 3"}
]
}
您可以使用map operator
来渲染动态ul > li
,如下所示:
<ul>
{
this.state.todos.map(todo => {
return <li key={todo.id}>{todo.text}</li>
})
}
</ul>