我想了解在 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/