将来自不同组件的参数作为 prop 传递回调函数

发布于 2025-01-09 03:16:44 字数 2523 浏览 3 评论 0原文

我知道标题不是很清楚,所以也许一个简化的例子会有所帮助。

我有一个负责翻译的反应组件(以下是一个超级简化的版本):

const data = {
  foo: {
    en: 'hello',
    es: 'hola'
  },
  bar: {
    en: 'world',
    es: 'mundo'
  }
  baz: {
    en: 'the answer is {PLACEHOLDER}',
    es: 'la respuesta es {PLACEHOLDER}'
  }
}

const Translation = ({strKey, param, lang}) => {
  const getTranslatedString = () => {
    const translation = data[strKey][lang]
    return (translation.indexOf('{PLACEHOLDER}') > -1 && param)
      ? translation.replace('{PLACEHOLDER}', param)
      : translation
  }
  
  return <p>getTranslatedString()</p>
}

Translation.defaultProps = {
  lang: 'en'
}

export default Translation;

我使用它如下:

<Translation strKey='baz' param={42} /> // renders as <p>the answer is 42</p>
<Translation strKey='baz' param={42} lang='es' /> // renders as <p>la respuesta es 42</p>

现在我必须修改我的 Translation 组件,以便我可以向它传递一个回调函数来操作翻译后的字符串。该函数需要将父组件中设置的一些参数以及 Translation 组件本身中设置的字符串作为输入。这就是我陷入困境的地方,因为我很难理解如何处理来自两个不同组件的参数:

const data = {
  foo: {
    en: 'hello#world',
    es: 'hola#mundo'
  }
}

// utility string manipulation function that will be used as callback
function getStringChunk(str, index) {
  return str.split('#')[index];
}

// Modified `Translation` component
const Translation = ({strKey, param, lang, callback}) => {
  const getTranslatedString = () => {
    const translation = data[strKey][lang]
    return (translation.indexOf('{PLACEHOLDER}') > -1 && param)
      ? translation.replace('{PLACEHOLDER}', param)
      : translation
  }
  
  return <p>{callback ? callback(getTranslatedString()) : getTranslatedString()}</p> // `callback` could be any function with any number of additional arguments 
}

const ParentComponent = ({isFirst}) => {
  return (
    <Translation
      strKey='foo'
      callback={() => {
        const index = isFirst ? 0 : 1;
        getStringChunk(index) // the function expects a first `str` argument but that is set inside the Translation component itself
      }}
    /> // should render either <p>hello</p> or <p>world</p>, depending on the value of `isFirst`
  );
}

我很确定我缺少一些非常基本和基本的东西,这些东西会让我觉得自己是个十足的白痴一旦有人指出解决方案,但我有某种“思维障碍”,我在原地打转却找不到解决方案。

提前致谢。

I know the title is not extremely clear so maybe a simplified example would help.

I have a react component in charge of translations (the following is a super-simplified version):

const data = {
  foo: {
    en: 'hello',
    es: 'hola'
  },
  bar: {
    en: 'world',
    es: 'mundo'
  }
  baz: {
    en: 'the answer is {PLACEHOLDER}',
    es: 'la respuesta es {PLACEHOLDER}'
  }
}

const Translation = ({strKey, param, lang}) => {
  const getTranslatedString = () => {
    const translation = data[strKey][lang]
    return (translation.indexOf('{PLACEHOLDER}') > -1 && param)
      ? translation.replace('{PLACEHOLDER}', param)
      : translation
  }
  
  return <p>getTranslatedString()</p>
}

Translation.defaultProps = {
  lang: 'en'
}

export default Translation;

I use it as follows:

<Translation strKey='baz' param={42} /> // renders as <p>the answer is 42</p>
<Translation strKey='baz' param={42} lang='es' /> // renders as <p>la respuesta es 42</p>

Now I have to modify my Translation component so that I can pass to it a callback function to manipulate the translated string. This function need to take as input some arguments set in the parent component and the string set in the Translation component itself. Here is where I am getting stuck, as I am having troubles understanding how to handle the arguments coming from two different components:

const data = {
  foo: {
    en: 'hello#world',
    es: 'hola#mundo'
  }
}

// utility string manipulation function that will be used as callback
function getStringChunk(str, index) {
  return str.split('#')[index];
}

// Modified `Translation` component
const Translation = ({strKey, param, lang, callback}) => {
  const getTranslatedString = () => {
    const translation = data[strKey][lang]
    return (translation.indexOf('{PLACEHOLDER}') > -1 && param)
      ? translation.replace('{PLACEHOLDER}', param)
      : translation
  }
  
  return <p>{callback ? callback(getTranslatedString()) : getTranslatedString()}</p> // `callback` could be any function with any number of additional arguments 
}

const ParentComponent = ({isFirst}) => {
  return (
    <Translation
      strKey='foo'
      callback={() => {
        const index = isFirst ? 0 : 1;
        getStringChunk(index) // the function expects a first `str` argument but that is set inside the Translation component itself
      }}
    /> // should render either <p>hello</p> or <p>world</p>, depending on the value of `isFirst`
  );
}

I am pretty sure there is something very fundamental and elementary I am missing, something that will make me feel as a complete idiot as soon as someone points out the solution, but I am having some kind of "mind block" and I am running in circles without finding a solution.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦旅人picnic 2025-01-16 03:16:44

也许你可以尝试这样的事情,

const ParentComponent = ({isFirst}) => {
  return (
    <div>
    <Translation
      strKey='foo'
      lang={'en'}
      callback={(mystr) => () => {
        const index = isFirst ? 0 : 1;
        return getStringChunk(mystr,index)
      }}
    /> 
    </div>
  );
}

我们创建一个通过接受字符串返回回调函数的函数。
那么您可以根据需要在 Translation

return

{callback ?回调(getTranslatedString())() : getTranslatedString()}

Maybe you could try something like this

const ParentComponent = ({isFirst}) => {
  return (
    <div>
    <Translation
      strKey='foo'
      lang={'en'}
      callback={(mystr) => () => {
        const index = isFirst ? 0 : 1;
        return getStringChunk(mystr,index)
      }}
    /> 
    </div>
  );
}

we make a function that returns the callback function by taking a string.
then you could create the callback function as required inside Translation

return <p>{callback ? callback(getTranslatedString())() : getTranslatedString()}</p>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文