[英]How to get React props outside component
我需要一種方法來加載此腳本的正確語言,並且該信息是props值。 粗略地說,它看起來像這樣:
class AddressInput extends React.Component {
render() {
return (
<PlacesAutocomplete
do={this.someStuff}
/>
);
}
}
export default scriptLoader(
`https://maps.googleapis.com/maps/api/js?&language=${this.props.language}`;
)(connect(mapStateToProps, mapDispatchToProps)(AddressInput));
我知道無法在組件外部訪問this.props
,所以我如何才能讓scriptLoader
獲得動態值?
您基本上就在那里。 您甚至有將其設置為HOC的想法。 這是實現:
function scriptLoader(WrappedComponent) {
return (props) => {
const dynamicUrl = `https://maps.googleapis.com/maps/api/js?&language=${props.language}`;
return <WrappedComponent {...props} url={dynamicUrl}/>
}
}
HOC接受一種稱為language
的道具,創建url,然后將其以道具名url
傳遞給包裝的組件。 顯然,您可以自行決定更改所有這些道具名稱。
// usage in the parent
<AddressInput language="en"/>
// what is available in your presentational component
class AddressInput extends React.Component {
render() {
console.log(this.props.url) // https://maps.googleapis.com/maps/api/js?&language=us
return (
<PlacesAutocomplete
do={this.someStuff}
/>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.