亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在返回方法中使用導入函數(無效的鉤子調用,react js)

在返回方法中使用導入函數(無效的鉤子調用,react js)

阿波羅的戰車 2023-05-11 16:17:10
伙計們,我有一個可重用的組件,它通過將鍵名作為字符串或綁定的 var 將鍵翻譯成一種選擇的語言。通常我為此使用標簽,但由于不同的原因,我將當前翻譯切換/替換為 {t('...')}。這是組件的代碼:import React from 'react';import { useTranslation as defaultTranslation } from 'react-i18next';import i18next from 'i18next';export const useTranslation = (ns = 'common', options) => {  return defaultTranslation(ns, {    useSuspense: false,    ...options,  });};export const withTranslation = (Component, ns, options) => {  const TranslatedHOC = (props) => {    const translationProps = useTranslation(ns, options);    return <Component {...translationProps} {...props} />;  };  return TranslatedHOC;};export const getCurrentLanguage = () =>  i18next.language || localStorage.getItem('language') || 'de-DE';首先,我為使用的導入函數定義常量:const {t} = useTranslation();正常情況:在文件中導入我的組件,我想在其中使用它并在上面添加代碼。我的組件代碼,我想在其中替換標簽。// Import React Tableimport ReactTable from 'react-table';import 'react-table/react-table.css';import LocalizedText from '@components/i18n/LocalizedText';class T extends React.Component {  constructor(props) {    super(props);    this.state = {      data: [],      pages: null,      loading: true,    };    this.fetchData = this.fetchData.bind(this);  }  fetchData(state, instance) {    this.props.onFetchData(state, instance).then(() => {      this.setState({        loading: false,      });    });  }  render() {    return (      <ReactTable        {...this.props}        previousText={          <LocalizedText textKey="caseoverview.orderproduct.back" />        }問題是,我無法使用上面引用的代碼而不會遇到任何有關無效掛鉤調用的問題。如果我以某種方式將其移出,則會收到錯誤消息,告訴我我的“t”未定義或意外標記。有人可以幫幫我嗎?在線搜索解決方案沒有任何結果。
查看完整描述

2 回答

?
慕標琳琳

TA貢獻1830條經驗 獲得超9個贊

鉤子只能在功能組件中使用。您可以將此類組件更改為功能組件,或者您可以使用react-i18nextwithTranslationHOC 來包裝您的類組件。

查看完整回答
反對 回復 2023-05-11
?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

使用 withTranslation 并傳遞t作為prop

const {t} = this.props;

渲染方法內部對我有用。


查看完整回答
反對 回復 2023-05-11
  • 2 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號