我正在学习反应js,现在我有一种情况,我不知道如何解决,也许你们中的一些人可以帮助我。
在我的webapplication中,我有一个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});
});
}
};
正如您所看到的,我使用道具显示selectedLanguage(默认情况下为&#34;英语&#34;):{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 */
});
}
};
我现在的问题是我不知道如何进行从孩子到父母的沟通,因为一旦用户选择了我想用所选语言更新下拉列表的语言,那么我需要的是填充方法handle单击以向父组件发送所选语言并更新它,但我不知道如何操作。到目前为止,我已经尝试过没有运气了
handleClick () {
$.get(this.props.url+"?code="+this.props.title,function(result){
this.props.selectedLanguage=this.props.title;
});
}
};
非常感谢任何帮助。
答案 0 :(得分:1)
您必须在LocaleSwitcher
组件中声明句柄点击,然后将其传递给ListItemWrapper
组件,就像您选择的语言一样。
你也可以传递道具中的事件。
所以你的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>);
}
答案 1 :(得分:1)
首先,将handleClick方法移动到LocaleSwitcher。
然后在LocaleSwitcher的render方法中执行:
render(){
return (<li>{this.props.selectedLanguage}
<ul className="dropdown">
{
this.state.languages.map(function(result,i){
return (<ListItemWrapper key={result.id} title={result.text} onclick={this.handleClick.bind(this,i)} url="language" />);
})
}
</ul>
</li>);
}
注意绑定,&#34; i&#34; map函数中的变量。
然后你的ListItemWrapper看起来像这样:
class ListItemWrapper extends React.Component{
constructor(props) {
super(props);
this.render = this.render.bind(this);
}
render () {
console.log("title:" + this.props.title);
return (<li onClick={this.props.handleClick}><a href="#">{this.props.title}</a></li>);
}
官方文档有一篇关于此的文章:
https://facebook.github.io/react/tips/communicate-between-components.html