我有一个来自我的 LanguageFlag 组件的道具“语言”,它根据语言插入一个 SVG 图标(如下所示)。在一个普通的功能组件中,我会通过一个 prop in 传递语言,然后将它作为语言 = {语言}添加到组件中。
在这种情况下<LanguageTitleOptions language={this.props.language}/>
,我读过我应该以这种方式添加它。但是如何将语言属性传递给我的 LandingPage 组件?
登陆页面组件
class LandingPage extends Component {
constructor(props) {
super(props);
this.state = {
formVisible: false,
earlyAccessSuccessVisible: false,
isMobile: this._getIsMobile(),
};
}
return (
<div className="buttons">
<LanguageTitleOptions
**language={this.props.language}/>**
<LanguageSelector/>
</LanguageTitleOptions>
</div>
LanguageFlag 组件
import React from "react";
import PropTypes from "prop-types";
import SpainFlag from "./SpainFlag";
import UKFlag from "./UKFlag";
const FLAGS = {
es: SpainFlag,
en: UKFlag,
};
const LanguageFlag = ({ language, ...otherProps }) => {
if (!language) return null;
const Flag = FLAGS[language];
return <Flag {...otherProps} />;
};
LanguageFlag.propTypes = {
language: PropTypes.oneOf(["es", "en"]),
};
export default LanguageFlag;
登陆页面容器
imports....
....
....
import LandingPage from "./LandingPage";
const mapStateToProps = (state) => {
return {
rootItemId: state.rootItemId,
};
};
const mapDispatchToProps = (dispatch) => {
return {
onRootItemAvailable: (rootItemId) => {
history.replace(generateItemPath(rootItemId));
},
onEarlyAccessRegistration: () => {
const anonymousId = getAnonymousId();
Meteor.call(TRACK_USER_REGISTERED_EMAIL, anonymousId);
},
};
};
const LandingPageContainer = connect(mapStateToProps, mapDispatchToProps)(LandingPage);
export default LandingPageContainer;
LanguageTitleOptions 组件
import React, { useEffect, useRef, useState } from "react";
import LanguageFlag from "/imports/cuadds/client/components/pages/settings/graphics/LanguageFlag";
import { Trans } from "@lingui/macro";
const LanguageTitleOptions = ({ language, className, children }) => {
const menu = useRef();
const [open, setOpen] = useState(false);
const handleClick = (e) => {
setOpen(!open);
};
const onWindowClick = (e) => {
// close menu if user clicked outside language selector menu element
if (!menu.current.contains(e.target)) {
setOpen(false);
}
};
useEffect(() => {
if (open) {
window.addEventListener("click", onWindowClick);
}
return () => {
window.removeEventListener("click", onWindowClick);
};
}, [open]);
return (
<div onClick={handleClick}>
<div className={className}>
<Trans>Language:</Trans>
<LanguageFlag language={language} width={18} style={{ marginLeft: 9 }} />
<i className="fa fa-angle-down"></i>
</div>
<div ref={menu}>{open && children}</div>
</div>
);
};
export default LanguageTitleOptions;