typescript 如何使用 ReactDOM 直接渲染 React 组件(ES6 API)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35599387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:18:26  来源:igfitidea点击:

How to render a React component (ES6 API) directly using ReactDOM?

reactjstypescriptecmascript-6react-dom

提问by Dynalon

I'm using the ES6 classes API of React(by using TypeScript) and want to render a subtyped class of type React.Componentusing ReactDOM.render().

我正在使用ReactES6 类 API(通过使用 TypeScript)并希望React.Component使用ReactDOM.render().

The following code works:

以下代码有效:

class MyComponentProps {
    someMember: string;
}

class MyComponent extends React.Component<MyComponentProps, {}> {
    constructor(initialProps: MyComponentProps) {
        super(initialProps);
    }
}

let rootNode = document.getElementById('root');
ReactDOM.render(
    <MyComponent someMember="abcdef" />,
    rootNode
)

Now, given the explicit typing of the constructor in react.d.ts, I'd assume I can pass an instance of the MyCustomProps object that populates with initial properties (as done in the above code). But how to render the component then directly without JSX/TSX syntax?

现在,鉴于构造函数在 中的显式类型react.d.ts,我假设我可以传递一个 MyCustomProps 对象的实例,该对象填充有初始属性(如上面的代码中所做的那样)。但是如何在没有 JSX/TSX 语法的情况下直接渲染组件呢?

The following does NOT work:

以下不起作用:

ReactDOM.render(new MyComponent(new MyComponentProps()), rootNode);

I know I could just use the JSX syntax as a workaround, but as my MyCustomPropsobject is pretty large, I don't want to repeat every member of the MyCustomPropsobject.

我知道我可以只使用 JSX 语法作为一种解决方法,但由于我的MyCustomProps对象非常大,我不想重复MyCustomProps对象的每个成员。

回答by WitVault

You should ues React.createElement. React.createElementtakes a tag name or component, a properties object, and variable number of optional child arguments. E.g.

你应该使用React.createElement. React.createElement采用标记名称或组件、属性对象和可变数量的可选子参数。例如

class App extends React.Component {
  render(){
    return (

      <div><h1>Welcome to React</h1></div>
    );
  }
}

Using jsxit can be rendered like this

使用jsx它可以像这样呈现

ReactDOM.render(<App />, document.getElementById('app'));

In another way(without jsx)

以另一种方式(没有jsx

ReactDOM.render(React.createElement(App, null), document.getElementById('app'));

A running example -

一个运行的例子 -

class App extends React.Component {
  render(){
    return (
      <div><h1>Welcome to React</h1></div>
    );
  }
}

ReactDOM.render(React.createElement(App, null), document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app">
</div>