[英]Transferring state between two components
我有一个searchForm组件,它呈现一个searchResult组件。 当searchForm获得结果时,应将状态传递给结果的state 。 这是我失败的地方。
var SearchForm = React.createClass({
getInitialState: function () {
return {
golden_record: {}
}
},
handleSearchSubmit: function (search_param) {
$.ajax({
url: this.props.url_variation,
type: 'GET',
data: search_param,
success: function (data) {
this.setState(
{
...
}
);
}.bind(this),
});
$.ajax({
url: this.props.url_golden,
type: 'GET',
data: search_param,
success: function (data) {
var golden_record = {
'site': data.sites[0].name,
'country': data.sites[0].country,
};
this.setState({'golden_record': golden_record});
}.bind(this),
})
},
render: function () {
return (
<div className="searchResult">
<SearchResult
golden_record={this.state.golden_record}
/>
</div>
);
}
});
搜索结果:
如您所见,我正在将golden_record
作为属性传递给SearchResult。 在SearchResult内部,当我将<input />
value
设置为属性this.props.golden_record['site']
,输入将固定为该值。 但是我想为this.state.site
设置值,以便以后可以更改它。 所以我不知道如何将prop的只读值复制到状态。
<input type="text" className="form-control" placeholder="Facility name" name="facilityName" onChange={this.onSiteChanged} value={this.props.golden_record['site']} ref="facilityName"></input>
有什么建议吗?
在SearchResult
组件中,可以在componentWillReceiveProps
设置状态:
var SearchResult = React.createClass({
...
getInitialState: function(){
return {
site: ''
}
},
componentDidMount: function(){
this.setState({ site: this.props.golden_record.site });
},
componentWillReceiveProps: function(newProps){
this.setState({ site: newProps.golden_record.site });
},
render: function(){
return <input type="text" className="form-control" placeholder="Facility name" name="facilityName" onChange={this.onSiteChanged} value={this.state.site} ref="facilityName"></input>
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.