与默认导入React的困惑

时间:2019-05-04 12:54:46

标签: javascript reactjs

要导入React,我们编写import React from 'react'

但这是默认的出口权吗?因此,如果我将其名称更改为 React 以外的其他名称,它也应该可以使用。但这是行不通的。谁能解释为什么?

2 个答案:

答案 0 :(得分:9)

本质上,JSX编译器(例如Babel / TypeScript)将JSX代码转换为纯JavaScript。

例如,以下JSX代码:

ngOnInit() {
  this.uniqueThreads =
    forkJoin(
      this.receivedMessages,
      this.sentMessages
    ).pipe(
      map(([receivedmessages, sentMessages]): Observable<{ username: string, thread: MessageModel[] }[]> => {
        let mergedThreads: { username: string, thread: MessageModel[] }[] = [];
        const messages: MessageModel[] = [...receivedmessages, ...sentMessages];
        messages.forEach((message) => {
          let activeThreadFrom = mergedThreads.find(any => any.username === message.fromUsername)
          if (activeThreadFrom === null) {
            mergedThreads.push({ username: message.fromUsername, thread: [message] })
          } else {
            activeThreadFrom.thread.push(message);
          }
          mergedThreads.push(activeThreadFrom);

          let activeThreadTo = mergedThreads.find(any => any.username === message.toUsername)
          if (activeThreadTo === null) {
            mergedThreads.push({ username: message.toUsername, thread: [message] })
          } else {
            activeThreadTo.thread.push(message);
          }
          mergedThreads.push(activeThreadTo)
        })
        return mergedThreads;
      })
    );
}

被编译为:

const Element = () => (
    <div>
        Hey there
    </div>
);

这是现在可以由浏览器解析的有效JavaScript。

您可能已经注意到,它使用const Element = () => ( React.createElement("div", null, "Hey there") ); 函数来创建React.createElement。这就是为什么更改导入名称不起作用的原因-编译器仍尝试使用div

如果需要,Babel允许您使用React选项configure this,从而允许您使用其他函数名称。

使用pragma编译器选项的TypeScript can do the same

答案 1 :(得分:0)

当您使用Babel或类似的东西来翻译JSX时,它是如此工作。 因此,当您输入如下内容:

TRAIN_DATA = [ ('Ich bin in Bremen', {'entities': [(11, 17, 'loc')]})] * 1000000



import spacy
import random
from spacy.util import minibatch, compounding

def train_spacy(data,iterations):
    TRAIN_DATA = data
    nlp = spacy.blank('de')  
    if 'ner' not in nlp.pipe_names:
        ner = nlp.create_pipe('ner')
        nlp.add_pipe(ner, last=True)


    # add labels
    for _, annotations in TRAIN_DATA:
         for ent in annotations.get('entities'):
            ner.add_label(ent[2])

    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']
    with nlp.disable_pipes(*other_pipes):  
        optimizer = nlp.begin_training()
        for itn in range(iterations):
            print("Statring iteration " + str(itn))
            random.shuffle(TRAIN_DATA)
            losses = {}  
            batches = minibatch(TRAIN_DATA, size=compounding(100, 64.0, 1.001))
            for batch in batches:        
                texts, annotations = zip(*batch)
                nlp.update(texts, annotations, sgd=optimizer, drop=0.35, losses=losses)
            print("Losses", losses)

    return nlp



model = train_spacy(TRAIN_DATA, 20)



您将获得下一个已转换的代码:

function AComponent() {
 return <div>Hello world</div>
}

由于这个原因,您应该使用React的确切名称。 您可以在这里尝试:https://babeljs.io/repl#?babili=false&browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=AQ4MwVwOwYwFwJYHsrAIIGEkFsAOKBTKOACgEpgBvAKFBACcC4J7UAeAEwQDcA-ACQIAbIUmAB3JPSEc2Aei59aoAL5A&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=7.4.4&externalPlugins=