繁体   English   中英

使用 Reactjs 在表格中显示项目

[英]display items in a table using Reactjs

我是 Reactjs 的完全初学者.. 这是一个简单的待办事项列表应用程序,我在 REACTJS 中有一些状态数据.. 我已经查看了所有代码并尝试以不同的方式进行操作。 但最后我控制台记录了该函数,但它返回 UNDEFINED。 一切都运行良好,但是应该显示项目列表的函数返回 UNDEFINED todoRows(),在 app.js 中返回 undefined

import React from 'react';
import NavBar from './components/NavBar';
import TodoRows from './components/TodoRows';

// Class App
export default class App extends React.Component{
     state ={ userName:  'Kouhadi aboubakr',
              todoItems:[
                         {action:'swimming', done:true},
                         {action:'calling daddy', done:false},
                         {action:'playing football', done:false}
             ],
             newTodo:    '',
           };
           
 updateValue=(e)=>{
   this.setState({
     newTodo:e.target.value
   });
 };

 addNewTodo = (e)=>{
   this.setState({
     todoItems:[
       ...this.state.todoItems, 
       {action:this.state.newTodo, done:false},
     ]
   })
   // clear the fields
   this.setState({newTodo:''});
 };

 todoRows = ()=>{
   this.state.todoItems.map(item =>{
      return  <TodoRows key={item.action} item={item} callback={this.toggleDone}/>; 
 })
 };

 toggleDone = (todo)=>{
   this.setState({
     todoItems:this.state.todoItems.map(item =>{
      return item.action === todo.action ? {...item, done:!item.done} : item
     })
   });
 };

 render=()=>{
   return(
     <div className='container'>
       <div className='row'>

         <NavBar name={this.state.userName}/>

         <div className='col-12'>
             <input
                   className='form-control'
                   value={this.state.newTodo}
                   onChange={this.updateValue}
             />
           <button className="btn btn-danger" onClick={this.addNewTodo}>Add</button>
         </div>
         <div className="col-12">
           <table className="table">
             <thead>
               <tr>
                 <th>Task</th>
                 <th>Completed</th>
               </tr>
             </thead>
             <tbody>
               {this.todoRows()}
                { /* WHEN I CONSOLE IT, IT RETUNS UNDEFINED  */}
             </tbody>
           </table>
         </div>
       </div>
     </div>
   );
 }
}
import React from 'react';

export default class TodoRows extends React.Component{

    render = ()=>{
        return         <tr>
        <td>{this.props.item.action}</td>
        <td>
          <input 
            type="checkbox" 
            checked={this.props.item.done}
            onChange={()=> this.props.callback(this.props.item)}
          />
        </td>
    </tr>
    }
}

您尝试在没有任何 DOM 的情况下调用函数,而 Todos 既不是状态也不是道具,请尝试在渲染中使用这个

 <tbody>{
  this.state.todoItems.map(item =>{
  return  <TodoRows key={item.action} item={item} callback={this.toggleDone}/>;
  }
 </tbody> 

暂无
暂无

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

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