我正在学习 React js,现在我遇到了一个不知道如何解决的情况,也许你们中的一些人可以帮助我。
在我的 Web 应用程序中,我有一个 React 组件,它表示用于选择语言的下拉菜单,如下所示:
class LocaleSwitcher extends React.Component{
constructor() {
super();
this.render = this.render.bind(this);
this.componentDidMount=this.componentDidMount.bind(this);
this.state = { languages:[] };
}
render(){
return (<li>{this.props.selectedLanguage}
<ul className="dropdown">
{
this.state.languages.map(function(result){
return (<ListItemWrapper key={result.id} title={result.text} url="language" />);
})
}
</ul>
</li>);
}
componentDidMount(){
var component = this;
$.get('data/languages',function(result){
component.setState({languages: result});
});
}
};
如您所见,我正在使用 props 显示 selectedLanguage(默认情况下为“english”):{this.props.selectedLanguage}
对于 li 元素,我创建了另一个组件 ListItemWrapper,我通过 props 进行父子通信:
class ListItemWrapper extends React.Component{
constructor() {
super();
this.render = this.render.bind(this);
this.handleClick =this.handleClick .bind(this);
}
render () {
console.log("title:" + this.props.title);
return (<li onClick={this.handleClick}><a href="#">{this.props.title}</a></li>);
}
handleClick () {
$.get(this.props.url+"?code="+this.props.title,function(result){
/*Insert the code here */
});
}
};
我现在的问题是我不知道如何进行 child 与 parent 之间的沟通,因为一旦用户选择了一种语言,我想用所选语言更新下拉列表,所以我需要填写方法 handleClick 将所选语言发送到父组件并更新它,但我不知道该怎么做。到目前为止,我已经尝试过了,但没有成功
handleClick () {
$.get(this.props.url+"?code="+this.props.title,function(result){
this.props.selectedLanguage=this.props.title;
});
}
};
任何帮助将不胜感激。
最佳答案
您必须在您的 LocaleSwitcher
组件中声明 handle click 并将其传递给 ListItemWrapper
组件,就像您传递的所选语言一样。
你也可以通过 props 传递事件。
所以你的 LocaleSwitcher 组件应该看起来像
handleClick () {
$.get(this.props.url+"?code="+this.props.title,function(result){
/*Insert the code here */
});
}
render(){
return (<li>{this.props.selectedLanguage}
<ul className="dropdown">
{
this.state.languages.map(function(result){
return (<ListItemWrapper key={result.id} title={result.text} url="language" handleClick={this.handleClick}/>);
})
}
</ul>
</li>);
}
你的 ListItemWrapper 组件看起来像
render () {
console.log("title:" + this.props.title);
return (<li onClick={this.props.handleClick}><a href="#">{this.props.title}</a></li>);
}
关于javascript - 通信子父 ReactJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34490627/