reactjs - 使用 React props vs import ,什么是最佳选择?

标签 reactjs

我想了解在 React 中使用 props 的最佳方式是什么

假设我有一个容器使用 import {FormattedMessage} from 'react-intl'

假设我在容器的 JSX 中使用了一个组件。

现在,如果我还想在组件中使用 FormattedMessage,我是否应该在组件中再次使用 import? 还是应该通过容器将 FormattedMessage 作为 prop 发送给组件?

例子:

import {FormattedMessage} from 'react-intl';

class Container {
   render() {
        return (
                <Component formattedMessage={FormattedMessage} />
        );
   }
}

最佳答案

<FormattedMessage/>是一个独立的组件,完全没有必要以这种方式将它传递给您的子组件。

如果您想将组件从父级传递给子级,请使用特殊属性 children相反。

<Container>渲染函数:

return (<Component><FormattedMessage /></Component>)

<Component>渲染函数:

return (<div>{props.children}</div>)

参见:https://reactjs.org/docs/composition-vs-inheritance.html

注意:如果你想将翻译后的字符串作为 prop 发送到你的子组件中,请使用 injectIntl传递 intl 的高阶组件支持你的组件。然后您可以调用 intl.formatMessage({id, defaultMessage})从您的组件内部将您要作为 Prop 传递的字符串翻译成您的子组件。

参见:https://github.com/yahoo/react-intl/wiki/API#injection-api

关于reactjs - 使用 React props vs import ,什么是最佳选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47272604/

相关文章:

reactjs - 如何对 fetch 完成后呈现的 React 组件进行单元测试?

reactjs - 如何将 React 和 Express 中重复出现的 Stripe 与自定义结账页面集成?

google-chrome-devtools - 如何在控制台中检查 react 元素的 Prop 和状态?

JavaScript 数组从索引中删除元素

javascript - Material 用户界面 : How to style filledInput component from an instance of the TextField component?

reactjs - 更新 componentDidMount 中的状态属性未反射(reflect)在 react 表中

javascript - 编译失败: <function name> is not defined no-undef

javascript - 类型错误 : Cannot read properties of null (reading 'useState' ) in Next. js

javascript - 更改循环中的组件状态

reactjs - 如何正确缩放页面上的 Dygraph?