简体   繁体   English

反应 如何传递带有参数的函数作为道具?

[英]React. How can I pass a function with a parameter as a prop?

I have a child component. 我有一个子组件。 In this component I'm trying to call function from parent component and pass in this function a parameter: 在此组件中,我尝试从父组件调用函数,并在此函数中传递参数:

Child component: 子组件:

class CartItem extends Component {
    constructor() {
        super();
        this.state = {
            id: ''
        }
    }

   componentDidMount() {
        this.setState({ id: this.props.cartItem.Id })
    }

    deleteHandler = () => {
        this.props.deleteItem(this.state.id);
    }

    render() {
      return ( <button onClick={this.deleteHandler}>Delete</button>);
 }
}

Parent coomponent: 父项

class OrderStepTwoIndex extends Component {
    constructor(props) {
        super(props);
        this.state = {
            deletedItemId: ''
        }
    }

  deleteItem = (id) => {
        debugger;
        this.setState(prevState => ({
            deletedItemId: { ...prevState.deletedItemId, id }
        }));
    }

  render() {
      return (
            {
              this.props.cartItems.map(function (item, key) {
                return <CartItem 
                            key={key} 
                            deleteItem={() => this.deleteItem()} 
                            cartItem={item} />
                                                })
            }
           );
    }
}

So, now I have an error: "Cannot read property 'deleteItem' of undefined" 所以,现在我有一个错误:“无法读取未定义的属性'deleteItem'”

Whenever you create function in javascript, it creates a scope with this . 每当您在javascript中创建function时,它都会使用this创建范围。 Arrow functions in comparison always take this from the outer scope. 相比之下,箭头功能始终从外部范围获得this功能。

So, try to use arrow function in map callback: 因此,尝试在map回调中使用箭头功能:

this.props.cartItems.map((item, key) => (
    <CartItem 
        key={key} 
        deleteItem={() => this.deleteItem()} 
        cartItem={item} />
)

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

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