gpt4 book ai didi

javascript - 单击链接时删除子组件

转载 作者:行者123 更新时间:2023-12-03 03:17:19 25 4
gpt4 key购买 nike

我现在正在教自己使用react,我有一个查看状态的组件,当添加新项目时,它会将一个子组件附加到自身。我现在想做的是通过单击删除添加的子组件。但是,我似乎无法获得链接停止的自然事件,如果我执行e.preventDefault(),我会得到preventDefault is not a function of undefined。

下面是我的代码,

    import React, { Component } from 'react';
import InvoiceForm from './InvoiceForm';
import InvoiceItemForm from './InvoiceItemForm';

class GenerateInvoice extends Component {

constructor(props) {
super(props);
this.state = {
invoice: {
items : []
}
};

this.onAddChild = this.onAddChild.bind(this);
this.removeItem = this.removeItem.bind(this);
}

render() {
const children = [];
for (var i = 0; i < this.state.invoice.items.length; i += 1) {
children.push(
<InvoiceItemForm
key={i}
number={i}
remove={this.removeItem} />
);
}
return(
<div>
<a href="" onClick={this.onAddChild}>Add New Item</a>
{children}
</div>
)
}

removeItem = (e, itemIndex) => {
e.stopPropagation();
alert("..removing...");
// let invoice = this.state.invoice;
// let updatedItems = this.state.invoice.items.splice(index, 1); //remove element
// let updateInvoice = { ...invoice, items:updatedItems}
// this.setState({ invoice }); //update state
}

onAddChild = (e) => {
e.preventDefault();
let invoice = this.state.invoice;
// creates an updated version of the items without changing the original value
let updatedItems = invoice.items.push({ 'id': 'INV001' });
// creates a new version of the invoice with the updated items
let updateInvoice = { ...invoice, items: updatedItems };
// update the invoice on the state to the new version
this.setState({ invoice });
}


}

导出默认GenerateInvoice;

子组件

    import React from 'react';

const InvoiceItemForm = (props) => {
console.log(props);
return(
<div>
<p>Hello {props.number}</p>
<a href="" onClick={props.remove(props.number)}>Remove</a>
</div>
)
}

export default InvoiceItemForm;

以及我的沙箱的链接,

https://codesandbox.io/s/0qx9w1qrwv

最佳答案

InvoiceItemForm 组件上,onClick={props.remove(props.number)},只有在这里您才可以引用事件对象。

您可以更改为:

onClick={(e) => {
e.preventDefault();
props.remove(props.number);
}}

编辑:

如果您想避免每次渲染都创建一个函数,您可以使用以下内容:

class InvoiceItemForm extends React.Component {
handleClick = (e) => {
e.preventDefault();
this.props.remove(props.number);
}

render() {
console.log(this.props);
return(
<div>
<p>Hello {this.props.number}</p>
<a href="" onClick={this.handleClick}>Remove</a>
</div>
)
}
}

关于javascript - 单击链接时删除子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46712176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com