Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

是不支持React类组件中使用吗? 还是我调用的有问题,请大佬帮忙指点一下 #45

Open
MichaelSammy opened this issue Sep 11, 2024 · 3 comments

Comments

@MichaelSammy
Copy link

1725969014388

@zhangfisher
Copy link
Owner

问题很清楚,你用的方式不对

不能在类组件中使用,要在函数式组件中使用

@MichaelSammy
Copy link
Author

这个项目是老项目了,组件都是类组件,我应该怎么解决这个问题,还请指点一下

@zhangfisher
Copy link
Owner

hook不支持在类组件中使用

你可以直接导入t函数来翻译即可。

import { t } from "./languages"

但是这样当切换语言时是不会动态切换的,你还需要解决一个当切换语言时如何重新渲染的问题。

觉得的方案也比较简单,就是侦听语言切换事件,然后重新渲染即可。

你可以编写一个I18nComponent ,让所有组件均继承此,如下:

class I18nComponent extends Component {
  componentDidMount() {
    // 添加 change 事件监听器
    VoerkaI18n.on('change', this.handleChange);
  }

  componentWillUnmount() {
    // 移除 change 事件监听器
    VoerkaI18n.off('change', this.handleChange);
  }

  handleChange = () => {
    // 强制重新渲染组件
    this.forceUpdate();
  };

  render() {
    return (
      <div>
        {/* 你的组件内容 */}
        <p>当前语言:{VoerkaI18n.getCurrentLanguage()}</p>
      </div>
    );
  }
}

export default MyComponent;

或者你也可以写一下HOC组件来干这活

function withI18n<T>(WrappedComponent: React.ComponentType<T>) {
    return (props: T) => {
        const [, setTick] = useState(0);

        useEffect(() => {
            const handleChange = () => {
                setTick(tick => tick + 1); // 强制重新渲染
            };

            VoerkaI18n.on('change', handleChange);

            return () => {
                VoerkaI18n.off('change', handleChange);
            };
        }, []);

        return <WrappedComponent {...props} />;
    };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants