点击下拉菜单链接后,如何更改语言下拉按钮图像以做出反应?

时间:2018-08-21 19:08:08

标签: reactjs

我正在尝试学习反应,因此,作为一项练习,我试图将我之前构建的静态html网站转换为反应。 该网站具有两种语言的内容:英语和德语。 我创建了一个自定义下拉菜单元素,其中包含一个带有US标志图像的按钮,该按钮可切换下拉菜单,而下拉菜单本身包含两个链接:第一个链接为英语的网站,另一个链接为德语的网站,每个链接均包含图片一个标志和一个跨度来命名语言。 我在Layout组件内使用react router导航到英语和德语,并且路由工作正常,但是在切换语言后切换下拉按钮标志图像时遇到了麻烦。

这是我的Dropdown组件的外观:

import React, { Component } from 'react';
import DropdownLink from './DropdownLink/DropdownLink';

import FlagEn from '../../../assets/images/lang/flag-en.svg';
import FlagDe from '../../../assets/images/lang/flag-de.svg';

class Dropdown extends Component {
    constructor() {
        super();

        this.state = {
            showMenu: false,
        };

        this.showMenu = this.showMenu.bind(this);
        this.closeMenu = this.closeMenu.bind(this);
    }

    showMenu(event) {
        event.preventDefault();

        this.setState({ showMenu: true }, () => {
            document.addEventListener('click', this.closeMenu);

        });
    }

    closeMenu(event) {    
        if (!this.dropdownMenu.contains(event.target) || this.dropdownMenu.contains(event.target)) {

            this.setState({ showMenu: false }, () => {
                document.removeEventListener('click', this.closeMenu);
            });  

        }
    }

    render() {
        const dropdownLinks = [
            { href: '../en', linkText: 'English', linkImg: FlagEn, imgAlt: 'English' },
            { href: '../de', linkText: 'Deutsch', linkImg: FlagDe, imgAlt: 'Deutsch' }
        ];
        let dropdownMenuShow = null;
        if (this.state.showMenu) {
            dropdownMenuShow = <div 
                className="dropdown-menu" 
                ref={(element) => {
                    this.dropdownMenu = element;
                }}>
                {dropdownLinks.map(dropdownLink => (
                    <DropdownLink 
                        onClick={this.showMenu}
                        href={dropdownLink.href} 
                        linkText={dropdownLink.linkText} 
                        key={dropdownLink.linkText} 
                        linkImg={dropdownLink.linkImg} 
                        imgAlt={dropdownLink.imgAlt} />
                ))}
            </div>
        }
        return (
            <div className="dropdown">
                <button className="dropdown-toggle" type="button" id="dropdownMenuButton" onClick={this.showMenu}>
                    <img src={FlagEn} alt="english" />
                </button>
                {dropdownMenuShow}
            </div>
        );
    }
}

export default Dropdown;

这是我的DropdownLink组件:

import React from 'react';
import { NavLink } from 'react-router-dom';

const dropdownLink = (props) => (
    <NavLink className="dropdown-item" to={props.href} exact>
        <img src={props.linkImg} alt={props.imgAlt} />
        <span>{props.linkText}</span>
    </NavLink>
);

export default dropdownLink;

有没有一种方法可以切换下拉按钮的标志图像,以便在选择英语时选择US标志,而在德语中选择德语标志? 链接路由到“ / en”和“ / de”。

2 个答案:

答案 0 :(得分:0)

这是您的类的粗略修订,它使用本地状态存储所选语言(因为您未指定存储方式)

import React, { Component } from 'react';
import DropdownLink from './DropdownLink/DropdownLink';

import FlagEn from '../../../assets/images/lang/flag-en.svg';
import FlagDe from '../../../assets/images/lang/flag-de.svg';

class Dropdown extends Component {
    constructor() {
        super();

        this.dropdownLinks = [
            { href: '../en', linkText: 'English', linkImg: FlagEn, imgAlt: 'English' },
            { href: '../de', linkText: 'Deutsch', linkImg: FlagDe, imgAlt: 'Deutsch' }
        ];

        this.state = {
            showMenu: false,
            selectedLanguage: this.dropdownLinks[0]
        };

        this.showMenu = this.showMenu.bind(this);
        this.setLanguage = this.setLanguage.bind(this);
        this.closeMenu = this.closeMenu.bind(this);
    }

    showMenu(event) {
        event.preventDefault();

        this.setState({ showMenu: true }, () => {
            document.addEventListener('click', this.closeMenu);

        });
    }

    setLanguage(language) {
        this.setState({selectedLanguage: language})
    }

    closeMenu(event) {    
        if (!this.dropdownMenu.contains(event.target) || this.dropdownMenu.contains(event.target)) {

            this.setState({ showMenu: false }, () => {
                document.removeEventListener('click', this.closeMenu);
            });  

        }
    }

    render() {
        let dropdownMenuShow = null;
        if (this.state.showMenu) {
            dropdownMenuShow = <div 
                className="dropdown-menu" 
                ref={(element) => {
                    this.dropdownMenu = element;
                }}>
                {this.dropdownLinks.map(dropdownLink => (
                    <DropdownLink 
                        onClick={() => this.setLanguage(dropdownLink)}
                        href={dropdownLink.href} 
                        linkText={dropdownLink.linkText} 
                        key={dropdownLink.linkText} 
                        linkImg={dropdownLink.linkImg} 
                        imgAlt={dropdownLink.imgAlt} />
                ))}
            </div>
        }
        return (
            <div className="dropdown">
                <button className="dropdown-toggle" type="button" id="dropdownMenuButton" onClick={this.showMenu}>
                    <img src={this.state.selectedLanguage.linkImg} alt="english" />
                </button>
                {dropdownMenuShow}
            </div>
        );
    }
}

export default Dropdown;

答案 1 :(得分:0)

您可以添加一个功能来更新按钮中显示的图像并将其向下传递到组件中。

    import React from 'react';
    import ReactDOM from 'react-dom';
    import DropdownLink from './DrowdownLink';

    export default class Test extends React.Component {
        constructor() {
            super();

            this.state = {
                showMenu: false,
                buttonFlag: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQb9JntXqHxGA9U_q4nJYzi1f5lzHWKReT3OwYNyydpNuFd9B0e'
            };

            this.showMenu = this.showMenu.bind(this);
            this.closeMenu = this.closeMenu.bind(this);
            this.updateFlag = this.updateFlag.bind(this);
        }

        showMenu(event) {
            event.preventDefault();

            this.setState({ showMenu: true }, () => {
                document.addEventListener('click', this.closeMenu);

            });
        }

        closeMenu(event) {
            if (!this.dropdownMenu.contains(event.target) || this.dropdownMenu.contains(event.target)) {

                this.setState({ showMenu: false }, () => {
                    document.removeEventListener('click', this.closeMenu);
                });

            }
        }

        updateFlag(link) {
            console.log(link);
            this.setState({ buttonFlag: link })
        }

        render() {
            const dropdownLinks = [
                { href: '../en', linkText: 'English', linkImg: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQb9JntXqHxGA9U_q4nJYzi1f5lzHWKReT3OwYNyydpNuFd9B0e', imgAlt: 'English' },
                { href: '../de', linkText: 'Deutsch', linkImg: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDqHreeGXhpRqWg8YwpjAPfv6_HXy7nEatEU8ec2KWxtI0LnBRLQ', imgAlt: 'Deutsch' }
            ];
            let dropdownMenuShow = null;
            if (this.state.showMenu) {
                dropdownMenuShow = <div
                    className="dropdown-menu"
                    ref={(element) => {
                        this.dropdownMenu = element;
                    }}>
                    {dropdownLinks.map(dropdownLink => (
                        <DropdownLink
                            onClick={this.showMenu}
                            href={dropdownLink.href}
                            linkText={dropdownLink.linkText}
                            key={dropdownLink.linkText}
                            linkImg={dropdownLink.linkImg}
                            updateFlag={this.updateFlag}
                            imgAlt={dropdownLink.imgAlt} />
                    ))}
                </div>
            }
            return (
                <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                    <button className="dropdown-toggle" type="button" id="dropdownMenuButton" onClick={this.showMenu}>
                        <img src={this.state.buttonFlag} alt="english" />
                    </button>
                    {dropdownMenuShow}
                </div>
            );
        }
    }

按钮的src现在从状态中拉出,状态从DropdownLink组件内部进行更新,并使用我们作为道具传递的函数 updateFlag 。而且我没有这些资源,所以我只使用了两个链接来在线标记图片。

这里是DropdownLink组件

    import React from 'react';
    import { NavLink } from 'react-router-dom';

    const dropdownLink = (props) => (
        <div className="dropdown-item" exact>
            <img onClick={() => props.updateFlag(props.linkImg)} src={props.linkImg} alt={props.imgAlt} />
            <span>{props.linkText}</span>
        </div>
    );

    export default dropdownLink;

希望有帮助!