【发布时间】:2016-04-02 03:10:06
【问题描述】:
我正在学习 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(默认为“英语”):{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 */
});
}
};
我现在的问题是我不知道如何进行从孩子到父母的沟通,因为一旦用户选择了一种语言,我想用所选语言更新下拉列表,所以我需要填写方法 handleClick 将所选语言发送到父组件并更新它,但我不知道该怎么做。到目前为止,我已经尝试过,但没有运气
handleClick () {
$.get(this.props.url+"?code="+this.props.title,function(result){
this.props.selectedLanguage=this.props.title;
});
}
};
任何帮助将不胜感激。
【问题讨论】:
标签: javascript jquery reactjs