Open YeonjuOHYE opened 4 years ago
<FormattedHTMLMessage
id="welcome"
defaultMessage={`<strong>Hello</strong> {name}, you have {count, number} {count, plural,
one {message}
other {messages}
}`}
values={{ name: name, count }}
/>
class FormattedHTMLMessage extends FormattedMessage<
Record<string, PrimitiveType>
> {
static displayName = 'FormattedHTMLMessage';
static defaultProps = {
...FormattedMessage.defaultProps,
tagName: 'span' as 'span',
};
render(): JSX.Element {
return (
<Context.Consumer>
{(intl): React.ReactNode => {
if (!this.props.defaultMessage) {
invariantIntlContext(intl);
}
const {formatHTMLMessage, textComponent} = intl;
const {
id,
description,
defaultMessage,
values: rawValues,
children,
} = this.props;
let {tagName: Component} = this.props;
// This is bc of TS3.3 doesn't recognize `defaultProps`
if (!Component) {
Component = textComponent || 'span';
}
const descriptor = {id, description, defaultMessage};
const formattedHTMLMessage = formatHTMLMessage(descriptor, rawValues);
if (typeof children === 'function') {
return children(formattedHTMLMessage);
}
// Since the message presumably has HTML in it, we need to set
// `innerHTML` in order for it to be rendered and not escaped by React.
// To be safe, all string prop values were escaped when formatting the
// message. It is assumed that the message is not UGC, and came from the
// developer making it more like a template.
//
// Note: There's a perf impact of using this component since there's no
// way for React to do its virtual DOM diffing.
const html = {__html: formattedHTMLMessage};
return <Component dangerouslySetInnerHTML={html} />;
}}
</Context.Consumer>
);
}
}
<div dangerouslySetInnerHTML={{ __html: t('my-label', { link: yourURL }) }} />
예시
https://github.com/formatjs/react-intl/tree/master/examples
Introduction
Creating an I18n Context
Formatting Data
Core Concepts
▶︎Formatters (Date, Number, Message, Relative)
▶︎Provider and Injector ▶︎API and Components ▶︎Message Descriptor 번역에 필요한 정보를 넘겨주는 객체
message extraction
▶︎Message Syntax ICU Message Syntax 기반으로 복잡한 syntax도 제공가능
▶︎Defining default messages for extraction ▶︎Custom, named formats
Component
Why Components? (API 직접 쓰는 것 보다 좋은 이유)
index
API
API 직접 쓰는 것 보다 <Formatted*> 사용하는 것이 더 많은 이점이 있다. API는 title, aria attribute 같이 ReactElement가 적합하지 않은 곳에 쓴다.
index
example
translations in files
js 파일
json