gpt4 book ai didi

javascript - 在react js中将数据从子组件发送到父组件

转载 作者:行者123 更新时间:2023-12-02 14:12:43 25 4
gpt4 key购买 nike

我使用Semantic-UI CSS Framework有一个下拉菜单。我想在下拉菜单上选择一个项目并知道选择了哪个项目。我可以知道在子组件中选择了哪个并设置了状态,但我无法发送父组件。实际上我是通过使用回调函数发送的,但是在设置父级状态时发生了循环并超出了内存。我关注了this way为此。

我的父组件是“SorguView”,子组件是“DropDownItem”

感谢您的帮助。

Solr 古级:

export class Sorgu {
_id:string;
userName:string;
anaSorgu:string;
aciklama:string;
sName:string;

constructor(id:string, username:string, anaSorgu:string, aciklama:string, sName:string) {
this._id = id;
this.userName = username;
this.anaSorgu = anaSorgu;
this.aciklama = aciklama;
this.sName=sName;
}
}

SorguProps 接口(interface):

export interface SorguProps {
sorgu:Sorgu;
}

SorguProps 接口(interface):

export interface SorguStates {
sorguList:Array<Sorgu>;
selectedName:string;
}

DropDownItem 组件(子组件):

class DropdownItem extends React.Component<SorguProps,SorguStates> {


constructor(props: SorguProps, context: any) {
super(props, context);
this.state = {
selectedName: 'no-data'
} as SorguStates;

this.calis = this.calis.bind(this);
}

calis = () => {
this.setState({selectedName: $('.item.active.selected').text()},() => console.log(""));

}


render() {
console.log("states",this.state);
console.log("props",this.props);
this.props.myFunc(this.state.selectedName);
return (

<div className="item" data-value={this.props.id} onClick={this.calis}>

{this.props.name}

</div>

);
}

}

SorguView(父级):

export class SorguView extends React.Component<SorguProps,SorguStates> {


constructor(props: SorguProps, context: any) {
super(props, context);
this.state = {
sorguList: [],
selectedName:''
} as SorguStates;


this.hello=this.hello.bind(this);



}



hello(data){

console.log("data=>"+data);
//this.setState({selectedName: data} as SorguStates); //Exceed memory
console.log("=>>>>"+ this.state.selectedName);

}

render(){

return (
<div className="ui selection dropdown" ref="dropSorgu">
<input type="hidden" name="selSorgu"/>
<div className="default text">Seçiniz</div>
<i className="dropdown icon"></i>
<div className="menu">

<DropdownItem name={this.state.sorguList[0].sName} id={this.state.sorguList[0].sName} myFunc={this.hello} />

</div>
</div>
);
}
}

最佳答案

子组件应该是“哑”的,并且不应该改变组件的状态。如果需要更改状态,它们应该简单地传递 props 并将数据传递回父级。

您将 hello 函数作为 prop myFunc 传递,这是正确的。然后,下拉项应调用该函数并向其传递必要的数据,以便父级可以设置所选项目的状态。

calis = () => {
this.props.myFunc($('.item.active.selected').text());
}

这将调用父组件中的 hello 函数,然后您可以从那里设置状态。

关于javascript - 在react js中将数据从子组件发送到父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39374251/

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