在React中将函数作为prop传递

时间:2018-02-18 13:13:37

标签: javascript reactjs

我想传递一个handleDelete函数作为道具。在子组件中,我想通过单击那里的按钮从列表中删除特定的Todo。

constructor(){
    super();
    this.state = {
        key:0,
        temp:'',
        list:[]
    }
}

handleList = () => {

    let { key,temp } = this.state;
    if (temp.length > 0 ) {
        let list = [...this.state.list];
        list.push(<Todo 
            delete = {()=>{this.handleDelete(key)}}
            text = {temp} 
            key = {key}/>);
        this.setState({
            list:list,
            key: this.state.key+1
        });
    }
}

handleDelete = (index) =>{
    let list = [...this.state.list];
    list.splice(index,1);
    this.setState({list});
    console.log('list',list.length);

}


render() {

    return(
        <div className = 'global'>

           <button onClick={() => {this.handleList()}
            }>Add-New</button>
           <button onClick={() => {this.handleDelete(key)}
            }>delete</button>
            <input 
                onChange = {
                    (e)=>{this.setState({
                        temp: e.target.value
                    })}
                }
                type = 'text' 
                placeholder = 'Enter New Todo!'/>
            <hr/>
     </div>

Todo组件

const Todo = (props) =>{
    return(
        <li>
            <h3>{props.text}</h3>
            <button onClick = {()=>
                props.delete
            }>Del</button>
            <hr/>
        </li>
    );
}

2 个答案:

答案 0 :(得分:2)

假设您的handleDelete功能完成了它所说的内容:您正在做的事情看起来应该有效,除非您实际上调用中的函数{ {1}}。

<Todo>中的原始处理程序调用一个返回传入函数的箭头函数,但无法调用传入函数本身。

将您的组件更改为调用在道具中传递的功能:

<Todo>

根据我原来答案的评论,可以进一步简化:

const Todo = (props) =>{
    return(
        <li>
            <h3>{props.text}</h3>
            <button onClick = {() => props.delete()}>Del</button>
            <hr/>
        </li>
    );
}

答案 1 :(得分:0)

如果要将handleDelete()作为属性传递,可以这样做。

在主要组件(带状态的组件)的返回中添加Todo。所以在div className =&#39; global&#39;下,您可以输入:

<Todo handleDelte={this.handleDelete} />

然后在您的Todo组件上使用它:

const Todo = ({handleDelete}) => {content}

另外,请确保在主要组件(带状态的组件)中导入Todo组件

相关问题