gpt4 book ai didi

javascript - 如何通过 onclick 子组件将数据传递给父组件 react

转载 作者:太空宇宙 更新时间:2023-11-04 01:27:44 25 4
gpt4 key购买 nike

如何使用 onclick 事件将数据从子组件传递到父组件。

我通常在我的应用程序中使用此代码。每当我单击按钮时,我都会在父组件 CreateEmail 中看到它被称为函数:

ƒ (selectedItem) {
var listofdata = _this.state.listofdata;
}

dddd = (selectedItem) => {
const { listofdata } = this.state;

const newList = [...listofdata];


const itemIndex = newList.findIndex(item => item.name === selectedItem.name);

if (itemIndex > -1) {
newList.splice(itemIndex, 1);
} else {
newList.push(selectedItem);
}

this.setState({
listofdata: newList
})

}

<CreateEmail dddd={this.dddd}/>

<button onClick={() => this.dddd(item)} className=" btn btn-info waves-effect waves-light" >+</button>

我只需要在单击按钮时获取数据。

最佳答案

假设这是您的parent.js

class parent extends React.Component{

dddd = (selectedItem) => {
const { listofdata } = this.state;

const newList = [...listofdata];


const itemIndex = newList.findIndex(item => item.name === selectedItem.name);

if (itemIndex > -1) {
newList.splice(itemIndex, 1);
} else {
newList.push(selectedItem);
}

this.setState({
listofdata: newList
})

}
render(){
return(
<CreateEmail dddd={this.dddd}/> //child component added
)
}
}

这是您的子组件CreateEmail.js

class CreateEmail extends React.Component{
constructor(props){
super(props);
this.state = {
item: '';
}
}
handleClick = () =>{
//here you should have logic to get data which you want to pass to parent component either maintain in state
this.props.dddd(this.state.item)
}
render(){
return(
<button onClick={() => this.handleClick} className=" btn btn-info waves-effect waves-light" >+</button>
)
}
}

关于javascript - 如何通过 onclick 子组件将数据传递给父组件 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56933758/

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