简体   繁体   English

如何在组件外部获取React道具

[英]How to get React props outside component

I need a way to load the correct language of this script, and that info is a props value. 我需要一种方法来加载此脚本的正确语言,并且该信息是props值。 Roughly put, it would look something like this: 粗略地说,它看起来像这样:

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));

I understand that this.props isn't accessible outside the component, so how would I be able to get scriptLoader to get a dynamic value? 我知道无法在组件外部访问this.props ,所以我如何才能让scriptLoader获得动态值?

You're basically there. 您基本上就在那里。 You even have the idea of making it an HOC. 您甚至有将其设置为HOC的想法。 Here is the impelementation: 这是实现:

function scriptLoader(WrappedComponent) {
  return (props) => {
    const dynamicUrl = `https://maps.googleapis.com/maps/api/js?&language=${props.language}`;
    return <WrappedComponent {...props} url={dynamicUrl}/>
  }
}

The HOC is accepting a prop called language , creates the url, and passes it down to the wrapped component, under the prop name url . HOC接受一种称为language的道具,创建url,然后将其以道具名url传递给包装的组件。 Obviously, all these prop names can be changed at your discretion. 显然,您可以自行决定更改所有这些道具名称。

// 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM