首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >ReactJS嵌套的组件属性为空

ReactJS嵌套的组件属性为空
EN

Stack Overflow用户
提问于 2020-04-22 03:10:08
回答 3查看 192关注 0票数 1

我正在尝试在ReactJS中嵌套一些组件,以便构建一个待办事项应用程序,但是当元素传递到映射函数中时,它是未定义的。

嵌套组件:

代码语言:javascript
代码运行次数:0
运行
复制
var El2= class App extends React.Component{
    constructor(props) { //constructor
        super(props);
        this.state = {
          todos: ['work out', 'eat breakfast', 'take a shower']/*,
        }
      }

    /**********methods**********/

    onDelete(item){
      let updatedTodos = this.state.todos.filter(function(val,index){
        return item!==val;
      });
      this.setState({todos:updatedTodos});
    }

    /********rendering method*******/

    render(){
      let todos = this.state.todos;
      todos=todos.map((item,index)=>{
        return(
          <TodoItem item={item} key={index} onDelete={this.onDelete}/>
        )
      })


        return(//works kinda like a main function
            <div id="todo-list"> 
                <p>the busiest people have the most leisure...</p>
                <ul>{todos}</ul>
            </div>
            );


    }//component rendering
}

嵌套组件:

代码语言:javascript
代码运行次数:0
运行
复制
//Creating TodoItem component

var TodoItem = class App extends React.Component{

  DeleteItem(){
    console.log(this); //trying to log the item outputs undefined
    this.props.onDelete(this.props.item);
  }

  render(){
    return(
      <li>
        <div className="todo-item">
          <span className="item-name">{this.props.item}</span>
          <span className="item-delete" onClick={this.DeleteItem}>X</span>
        </div>
      </li>
    );
  }
}

当我点击X时,我得到"TypeError: Cannot read property 'props‘of undefined“。我怎么才能解决这个问题,并真正成功地删除对象呢?

EN

回答 3

Stack Overflow用户

发布于 2020-04-22 03:25:38

您的代码中有几个问题。

  1. 类定义

或者使用类组件

代码语言:javascript
代码运行次数:0
运行
复制
class TodoItem extends React.Component {
}

或函数组件

代码语言:javascript
代码运行次数:0
运行
复制
const TodoItem = ({...}) => {
 return (
   <li>
    ...
   </li>
 )
}

函数组件必须以不同的方式编写,并且没有this对象。所以可以先使用类组件

  1. DeleteItem method

常识是在开始时使用小字符,以便deleteItem,但这不是问题。标准方法不受此约束,因此您必须手动执行此操作

代码语言:javascript
代码运行次数:0
运行
复制
 <span className="item-delete" onClick={this.DeleteItem.bind(this)}>X</span>

更好和更简单的解决方案是使用箭头函数,该函数将自动绑定。

代码语言:javascript
代码运行次数:0
运行
复制
  DeleteItem = () => {
    console.log(this); //trying to log the item outputs undefined
    this.props.onDelete(this.props.item);
  }
票数 0
EN

Stack Overflow用户

发布于 2020-04-22 03:27:11

您没有在构造函数内部绑定this.onDeletethis.DeleteItem。您可以对您各自的2个组件执行this.onDelete = this.onDelete.bind(this);this.DeleteItem = this.DeleteItem.bind(this);。请参考以下代码

代码语言:javascript
代码运行次数:0
运行
复制
var El2 = class App extends React.Component {
  constructor(props) {
    //constructor
    super(props);
    this.state = {
      todos: ["work out", "eat breakfast", "take a shower"]
    };
    this.onDelete = this.onDelete.bind(this);
  }

  /**********methods**********/

  onDelete(item) {
    console.log(item, this.state.todos);
    let updatedTodos = this.state.todos.filter((val, index) => {
      return item !== val;
    });
    this.setState({ todos: updatedTodos });
  }

  /********rendering method*******/

  render() {
    let todos = this.state.todos;
    todos = todos.map((item, index) => {
      return <TodoItem item={item} key={index} onDelete={this.onDelete} />;
    });

    return (
      //works kinda like a main function
      <div id="todo-list">
        <p>the busiest people have the most leisure...</p>
        <ul>{todos}</ul>
      </div>
    );
  } //component rendering
}
代码语言:javascript
代码运行次数:0
运行
复制
var TodoItem = class App extends React.Component {
  constructor(props) {
    super(props);
    this.DeleteItem = this.DeleteItem.bind(this);
  }

  DeleteItem() {
    console.log(this.props); //trying to log the item outputs undefined
    this.props.onDelete(this.props.item);
  }

  render() {
    return (
      <li>
        <div className="todo-item">
          <span className="item-name">{this.props.item}</span>
          <span className="item-delete" onClick={this.DeleteItem}>
            X
          </span>
        </div>
      </li>
    );
  }
};
票数 0
EN

Stack Overflow用户

发布于 2020-04-22 03:52:29

您需要查看有关端口和组件https://pt-br.reactjs.org/docs/components-and-props.html的更多信息

我还建议不要创建这样的类。今天,react推荐制作功能组件。

如下所示:

代码语言:javascript
代码运行次数:0
运行
复制
import React, { useEffect, useState } from "react";

function App(){

const [todos, setTodos] = useState("");           ** hooks to create state**

 useEffect(() => {
                                        ** acess life cicle 
  }, [todos])                           **in this array is variable react obrseve to update**

----heres come your functions ------

return(
   <div id="todo-list"> 
    <p>the busiest people have the most leisure...</p>
    <ul>{todos}</ul>
  </div>
){

 }
}
´´´´
See in documentation about hook in link 
<https://pt-br.reactjs.org/docs/hooks-intro.html> 
has an example similar to what you are trying to do. 
I went a little far in explaining it but I believe it is useful.

I hope I helped.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61351303

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档